Jensen's Device: Difference between revisions

no edit summary
mNo edit summary
No edit summary
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;
 
Line 63:
Put_Line (Float'Image (Sum (I'Access, 1.0, 100.0, Inv_I'Access)));
end Jensen_Device;
</adalang>
<pre>
5.18738E+00
Line 89:
 
=={{header|C}}==
<lang cpp>#include <stdio.h>
 
int i;
Line 104:
printf("%f\n", sum(&i, 1, 100, term_func));
return 0;
}</cpplang>
Output: 5.18738
 
=={{header|C++}}==
<lang cpp>#include <iostream>
 
int i;
Line 123:
std::cout << sum(i, 1, 100, term_func) << std::endl;
return 0;
}</cpplang>
Output: 5.18738
 
=={{header|E}}==
 
In E, the distinct mutable locations behind assignable variables can be reified as [http://wiki.erights.org/wiki/Slot Slot] objects. The E language allows a variable name (''noun'') to be bound to a particular slot, and the slot of an already-bound noun to be extracted, using the <codett>&</codett> operator.
 
(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>.)
Line 147:
}
 
<codett>1/i</codett> is not a noun, so there is no slot associated with it; so we use <codett>def _.get() { return 1/i }</codett> to define a slot object which does the computation when it is read as a slot.
 
The value returned by the above program (expression) is 5.187377517639621.
Line 179:
 
=={{header|OCaml}}==
<lang ocaml>let i = ref 42 (* initial value doesn't matter *)
 
let sum' i lo hi term =
Line 191:
 
let () =
Printf.printf "%f\n" (sum' i 1 100 (fun () -> 1. /. float !i))</ocamllang>
Output: 5.187378
 
=={{header|Perl}}==
<lang perl>my $i;
sub sum {
my ($i, $lo, $hi, $term) = @_;
Line 205:
}
 
print sum(\$i, 1, 100, sub { 1 / $i }), "\n";</perllang>
Output: 5.18737751763962
 
Or you can take advantage of the fact that elements of the @_ are aliases of the original:
<lang perl>my $i;
sub sum {
my (undef, $lo, $hi, $term) = @_;
Line 219:
}
 
print sum($i, 1, 100, sub { 1 / $i }), "\n";</perllang>
Output: 5.18737751763962
 
=={{header|PHP}}==
<lang php>$i;
function sum (&$i, $lo, $hi, $term) {
$temp = 0;
Line 232:
}
 
echo sum($i, 1, 100, create_function('', 'global $i; return 1 / $i;')), "\n";</phplang>
Output: 5.18737751764
 
=={{header|Python}}==
<lang python>class Ref(object):
def __init__(self, value=None):
self.value=value
Line 251:
# note the correspondence between the mathematical notation and the call to sum
# it's almost as good as sum(1/i for i in range(1,101))
print (sum (i, 1, 100, lambda: 1.0/i.value))</pythonlang>
Output: 5.18737751764