Anonymous user
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;
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}}
<
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>
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>
<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:
=={{header|Haskell}}==
<lang haskell>import Control.Monad▼
▲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>
Output: 5.187377517639621
Line 273 ⟶ 267:
=={{header|M4}}==
<lang M4>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>
Output:
Line 379 ⟶ 371:
But here is the Ruby way to do it:
<lang ruby
lo.upto(hi).inject(0.0) {|sum, n| sum += yield n}
end
|