Jensen's Device: Difference between revisions

m
Fixed lang tags.
(C# code)
m (Fixed lang tags.)
Line 36:
[http://en.wikipedia.org/wiki/Donald_Knuth Donald Knuth] later proposed the [[Man or boy test|Man or Boy Test]] as a more rigorous exercise.
=={{header|Ada}}==
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
 
procedure Jensen_Device is
Line 62 ⟶ 61:
begin
Put_Line (Float'Image (Sum (I'Access, 1.0, 100.0, Inv_I'Access)));
end Jensen_Device;</lang>
</lang>
<pre>
5.18738E+00
Line 69 ⟶ 67:
=={{header|ALGOL 68}}==
{{trans|ALGOL 60}}
<prelang algol68>BEGIN
INT i;
PROC sum = (REF INT i, INT lo, hi, PROC REAL term)REAL:
Line 84 ⟶ 82:
COMMENT note the correspondence between the mathematical notation and the call to sum COMMENT
print (sum (i, 1, 100, REAL: 1/i))
END</lang>
</pre>
Output: +5.18737751763962e +0
 
Line 151 ⟶ 148:
Console.WriteLine(Sum(ref i, 1, 100, () => 1.0 / i));
}
}</lang>
}
</lang>
 
=={{header|Common Lisp}}==
Line 213 ⟶ 209:
(The definition of the outer <var>i</var> has been moved down to emphasize that it is unrelated to the <var>i</var> inside of <var>sum</var>.)
 
<lang e>pragma.enable("one-method-object") # "def _.get" is experimental shorthand
def sum(&i, lo, hi, &term) { # bind i and term to passed slots
var temp := 0
i := lo
while (i <= hi) { # E has numeric-range iteration but it creates a distinct
temp += term # variable which would not be shared with the passed i
i += 1
}
return temp
}
{
var i := null
sum(&i, 1, 100, def _.get() { return 1/i })
}</lang>
}
 
<tt>1/i</tt> is not a noun, so there is no slot associated with it; so we use <tt>def _.get() { return 1/i }</tt> to define a slot object which does the computation when it is read as a slot.
Line 234 ⟶ 230:
This emulation of the original call-by-name is of course unidiomatic; a natural version of the same computation would be:
 
<lang e>def sum(lo, hi, f) {
var temp := 0
for i in lo..hi { temp += f(i) }
return temp
}
sum(1, 100, fn i { 1/i })</lang>
 
=={{header|Haskell}}==
<lang haskell>import Control.Monad
<pre>
import Control.Monad
import Control.Monad.ST
import Data.STRef
Line 255 ⟶ 250:
sum' i 1 100 $ return recip `ap` readSTRef i
 
main = print foo</lang>
</pre>
Output: 5.187377517639621
 
Line 273 ⟶ 267:
 
=={{header|M4}}==
<lang M4>define(`for',
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
Line 281 ⟶ 274:
`pushdef(`temp',0)`'for(`$1',$2,$3,
`define(`temp',eval(temp+$4))')`'temp`'popdef(`temp')')
sum(`i',1,100,`1000/i')</lang>
</lang>
 
Output:
Line 379 ⟶ 371:
 
But here is the Ruby way to do it:
<lang ruby >def sum2(lo, hi)
lo.upto(hi).inject(0.0) {|sum, n| sum += yield n}
end
Anonymous user