Jensen's Device: Difference between revisions

Added Dart
(Realize in F#)
(Added Dart)
 
(45 intermediate revisions by 23 users not shown)
Line 32:
[[wp:Donald_Knuth|Donald Knuth]] later proposed the [[Man or boy test|Man or Boy Test]] as a more rigorous exercise.
<br><br>
 
=={{header|11l}}==
{{trans|C#}}
 
<syntaxhighlight lang="11l">F sum(&i, lo, hi, term)
V temp = 0.0
i = lo
L i <= hi
temp += term()
i++
R temp
 
F main()
Int i
print(sum(&i, 1, 100, () -> 1 / @i))
 
main()</syntaxhighlight>
 
{{out}}
<pre>
5.18738
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Jensen_Device is
Line 59 ⟶ 81:
begin
Put_Line (Float'Image (Sum (I'Access, 1.0, 100.0, Inv_I'Access)));
end Jensen_Device;</langsyntaxhighlight>
<pre>
5.18738E+00
Line 86 ⟶ 108:
=={{header|ALGOL 68}}==
{{trans|ALGOL 60}}
<langsyntaxhighlight lang="algol68">BEGIN
INT i;
PROC sum = (REF INT i, INT lo, hi, PROC REAL term)REAL:
Line 101 ⟶ 123:
COMMENT note the correspondence between the mathematical notation and the call to sum COMMENT
print (sum (i, 1, 100, REAL: 1/i))
END</langsyntaxhighlight>
Output: +5.18737751763962e +0
 
=={{header|ALGOL W}}==
{{Trans|ALGOL 68}}
Algol W retained Algol 60's call by name but also offered additional parameter passing modes.
<br>This version uses call by name for the i parameter but uses a procedure parameter for the summed expression.
<br>The expression supplied in the call is automatically converted to a procedure by the compiler.
<syntaxhighlight lang="algolw">begin
integer i;
real procedure sum ( integer %name% i; integer value lo, hi; real procedure term );
% i is passed by-name, term is passed as a procedure which makes it effectively passed by-name %
begin
real temp;
temp := 0;
i := lo;
while i <= hi do begin % The Algol W "for" loop (as in Algol 68) creates a distinct %
temp := temp + term; % variable which would not be shared with the passed "i" %
i := i + 1 % Here the actual passed "i" is incremented. %
end while_i_le_temp;
temp
end;
% note the correspondence between the mathematical notation and the call to sum %
write( sum( i, 1, 100, 1/i ) )
end.</syntaxhighlight>
{{out}}
<pre>
</pre>
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">set i to 0
 
on jsum(i, lo, hi, term)
Line 121 ⟶ 169:
end script
 
return jsum(a reference to i, 1, 100, term_func)</langsyntaxhighlight>
Output: 5.18737751764
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 211 ⟶ 259:
fUn: .float 1
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
{{trans|Ruby}}
<syntaxhighlight lang="rebol">harmonicSum: function [variable, lo, hi, term][
result: new 0.0
loop lo..hi 'n ->
'result + do ~"|variable|: |n| |term|"
result
]
print ["harmonicSum 1->100:" harmonicSum 'i 1 100 {1.0 / i}]</syntaxhighlight>
{{out}}
<pre>harmonicSum 1->100: 5.187377517639621</pre>
 
=={{header|Asymptote}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="Asymptote">real temp = 0;
for(int i = 1; i <= 100; ++i) {
temp += 1/i;
}
write(temp);</syntaxhighlight>
{{out}}
<pre>5.18737751763962</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f JENSENS_DEVICE.AWK
# converted from FreeBASIC
BEGIN {
evaluation()
exit(0)
}
function evaluation( hi,i,lo,tmp) {
lo = 1
hi = 100
for (i=lo; i<=hi; i++) {
tmp += (1/i)
}
printf("%.15f\n",tmp)
}
</syntaxhighlight>
{{out}}
<pre>
5.187377517639621
</pre>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
Same code as [[#GW-BASIC|GW-BASIC]]
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
call Evaluation()
end
 
subroutine Evaluation()
lo = 1 : hi = 100 : temp = 0
for i = lo to hi
temp += (1/i) ##r(i)
next i
print temp
end subroutine</syntaxhighlight>
{{out}}
<pre>5.18737751764</pre>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> PRINT FNsum(j, 1, 100, FNreciprocal)
END
Line 225 ⟶ 337:
= temp
DEF FNreciprocal = 1/i</langsyntaxhighlight>
Output:
<pre>5.18737752</pre>
 
5.18737752
==={{header|Chipmunk Basic}}===
</pre>
{{trans|QBasic}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 call evaluation
110 end
120 sub evaluation()
130 lo = 1
140 hi = 100
150 temp = 0
160 for i = lo to hi
170 temp = temp+(1/i)
180 next i
190 print temp
200 end sub</syntaxhighlight>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">precision 4
 
define lo = 1, hi = 100, temp = 0
 
for i = lo to hi
 
let temp = temp + (1 / i)
wait
 
next i
 
print temp</syntaxhighlight>
{{out| Output}}<pre>5.1873</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="vbnet">Sub Evaluation
Dim As Integer i, lo = 1, hi = 100
Dim As Double temp = 0
For i = lo To hi
temp += (1/i) ''r(i)
Next i
Print temp
End Sub
 
Evaluation
Sleep</syntaxhighlight>
{{out}}
<pre>5.187377517639621</pre>
 
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">local fn JensensDevice( lo as long, hi as long ) as double
double i, temp = 0.0
for i = lo to hi
temp = temp + (1/i)
next
end fn = temp
 
print fn JensensDevice( 1, 100 )
 
HandleEvents</syntaxhighlight>
{{output}}
<pre>5.187377517639621</pre>
 
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Sub Evaluation()
 
Dim i As Integer, lo As Integer = 1, hi As Integer = 100
Dim tmp As Float = 0
 
For i = lo To hi
tmp += (1 / i)
Next
Print tmp
 
End Sub
 
Public Sub Main()
 
Evaluation
 
End </syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|QBasic}}
{{works with|QB64}}
{{works with|Quite BASIC}}
{{works with|MSX BASIC}}
<syntaxhighlight lang="qbasic">100 GOSUB 120
110 END
120 REM Evaluation
130 LET A = 1
140 LET B = 100
150 LET T = 0
160 FOR I = A TO B
170 LET T = T + (1/I)
180 NEXT I
190 PRINT T
200 RETURN</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">100 GOSUB 120
110 GOTO 210
120 REM Evaluation
130 LET A = 1
140 LET B = 100
150 LET T = 0
160 FOR I = A TO B
170 LET T = T+(1/I)
180 NEXT I
190 PRINT T
200 RETURN
210 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
Same code as [[#GW-BASIC|GW-BASIC]]
 
==={{header|PureBasic}}===
{{trans|C}}
<syntaxhighlight lang="purebasic">Prototype.d func()
 
Global i
 
Procedure.d Sum(*i.Integer, lo, hi, *term.func)
Protected Temp.d
For i=lo To hi
temp + *term()
Next
ProcedureReturn Temp
EndProcedure
 
Procedure.d term_func()
ProcedureReturn 1/i
EndProcedure
 
Answer.d = Sum(@i, 1, 100, @term_func())</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{works with|Run BASIC}}
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
{{works with|True BASIC}}
<syntaxhighlight lang="qbasic">CALL EVALUATION
END
 
SUB Evaluation
LET lo = 1
LET hi = 100
LET temp = 0
FOR i = lo TO hi
LET temp = temp + (1 / i)
NEXT i
PRINT temp
END SUB</syntaxhighlight>
 
==={{header|QB64}}===
Same code as [[#QBasic|QBasic]]
 
==={{header|Quite BASIC}}===
Same code as [[#GW-BASIC|GW-BASIC]]
 
==={{header|Run BASIC}}===
Same code as [[#QBasic|QBasic]]
 
==={{header|True BASIC}}===
Same code as [[#QBasic|QBasic]]
 
==={{header|uBasic/4tH}}===
Since uBasic/4tH does not support floating point numbers, fixed point has to be used. Of course, precision suffers significantly.
<syntaxhighlight lang="qbasic">' ** NOTE: it requires a 64-bit uBasic; number ranges are limited. **
 
If Info("wordsize") < 64 Then Print "This program requires a 64-bit uBasic" : End
 
Dim @i(1)
i = 0 ' fake something that resembles a pointer
 
Print Using "+?.####";FUNC(_Ftoi(FUNC(_Sum(i, 1, 100, _Term))))
End
 
_Sum
Param (4)
Local (1)
 
e@ = 0
For @i(a@) = b@ To c@ : e@ = e@ + FUNC(d@) : Next
 
Return (e@)
 
_Term Return (FUNC(_Fdiv(1, @i(i))))
_Fdiv Param (2) : Return ((a@*16384)/b@)
_Ftoi Param (1) : Return ((10000*a@)/16384)</syntaxhighlight>
{{Out}}
<pre>5.1850
 
0 OK, 0:313 </pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">Evaluation()
end
 
sub Evaluation()
lo = 1 : hi = 100 : temp = 0
for i = lo to hi
temp = temp + (1/i) //r(i)
next i
print temp
end sub</syntaxhighlight>
{{out}}
<pre>5.18738</pre>
 
==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="qbasic">10 DEF FN r(x)=1/x
20 LET f$="FN r(i)"
30 LET lo=1: LET hi=100
40 GO SUB 1000
50 PRINT temp
60 STOP
1000 REM Evaluation
1010 LET temp=0
1020 FOR i=lo TO hi
1030 LET temp=temp+VAL f$
1040 NEXT i
1050 RETURN </syntaxhighlight>
{{out}}
<pre>5.1873775</pre>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( sum
= I lo hi Term temp
. !arg:((=?I),?lo,?hi,(=?Term))
Line 245 ⟶ 585:
)
& sum$((=i),1,100,(=!i^-1))
);</langsyntaxhighlight>
Output:
<pre>14466636279520351160221518043104131447711/2788815009188499086581352357412492142272</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int i;
Line 265 ⟶ 605:
printf("%f\n", sum(&i, 1, 100, term_func));
return 0;
}</langsyntaxhighlight>
Output: 5.18738
 
{{works with|gcc}}
Alternatively, C's macros provide a closer imitation of ALGOL's call-by-name semantics:
<langsyntaxhighlight lang="c">#include <stdio.h>
int i;
Line 288 ⟶ 628:
printf("%f\n", sum(i, 1, 100, 1.0 / i));
return 0;
}</langsyntaxhighlight>
Output: 5.187378
 
=={{header|C sharp}}==
Can be simulated via lambda expressions:
<langsyntaxhighlight lang="csharp">using System;
 
class JensensDevice
Line 312 ⟶ 652:
Console.WriteLine(Sum(ref i, 1, 100, () => 1.0 / i));
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
 
Line 338 ⟶ 678:
std::cout << SUM(i,1,100,1.0/i) << "\n";
return 0;
}</langsyntaxhighlight>
Output: 5.18738
5.18738
Line 344 ⟶ 684:
=={{header|Clipper}}==
With hindsight Algol60 provided this feature in a way that is terrible for program maintenance, because the calling code looks innocuous.
<langsyntaxhighlight Clipperlang="clipper">// Jensen's device in Clipper (or Harbour)
// A fairly direct translation of the Algol 60
// John M Skelton 11-Feb-2012
Line 364 ⟶ 704:
next i
return temp
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 370 ⟶ 710:
Common Lisp does not have call-by-name for functions; however, it can be directly simulated by a macro wrapping selected parameters in lambdas.
 
<langsyntaxhighlight lang="lisp">(declaim (inline %sum))
 
(defun %sum (lo hi func)
Line 376 ⟶ 716:
 
(defmacro sum (i lo hi term)
`(%sum ,lo ,hi (lambda (,i) ,term)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">CL-USER> (sum i 1 100 (/ 1 i))
14466636279520351160221518043104131447711/2788815009188499086581352357412492142272
CL-USER> (float (sum i 1 100 (/ 1 i)))
5.1873775</langsyntaxhighlight>
 
=={{header|D}}==
There are better ways to do this in D, but this is closer to the original Algol version:
<langsyntaxhighlight lang="d">double sum(ref int i, in int lo, in int hi, lazy double term)
pure @safe /*nothrow @nogc*/ {
double result = 0.0;
Line 398 ⟶ 738:
int i;
sum(i, 1, 100, 1.0/i).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>5.18738</pre>
 
=={{header|Dart}}==
{{trans|C++}}
<syntaxhighlight lang="dart">double i = 0;
double sum(int lo, int hi, double Function() term) {
double temp = 0;
for (i = lo.toDouble(); i <= hi; i++) temp += term();
return temp;
}
 
double termFunc() {
return 1.0 / i;
}
 
void main() {
print(sum(1, 100, termFunc));
}</syntaxhighlight>
{{out}}
<pre>5.187377517639621</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
 
type TTerm = function(i: integer): real;
 
function Term(I: integer): double;
begin
Term := 1 / I;
end;
 
 
function Sum(var I: integer; Lo, Hi: integer; Term: TTerm): double;
begin
Result := 0;
I := Lo;
while I <= Hi do
begin
Result := Result + Term(I);
Inc(I);
end;
end;
 
 
procedure ShowJensenDevice(Memo: TMemo);
var I: LongInt;
begin
Memo.Lines.Add(FloatToStrF(Sum(I, 1, 100, @Term), ffFixed,18,15));
end;
 
 
 
 
</syntaxhighlight>
{{out}}
<pre>
5.187377517639621
5.18738</pre>
 
Elapsed Time: 1.037 ms.
 
</pre>
 
 
=={{header|DWScript}}==
Must use a "while" loop, as "for" loop variables are restricted to local variable for code clarity, and this indeed a case where any kind of extra clarity helps.
<langsyntaxhighlight lang="delphi">function sum(var i : Integer; lo, hi : Integer; lazy term : Float) : Float;
begin
i:=lo;
Line 416 ⟶ 821:
var i : Integer;
 
PrintLn(sum(i, 1, 100, 1.0/i));</langsyntaxhighlight>
Output: 5.187...
 
Line 425 ⟶ 830:
(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>.)
 
<langsyntaxhighlight 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
Line 438 ⟶ 843:
var i := null
sum(&i, 1, 100, def _.get() { return 1/i })
}</langsyntaxhighlight>
 
<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 446 ⟶ 851:
This emulation of the original call-by-name is of course unidiomatic; a natural version of the same computation would be:
 
<langsyntaxhighlight 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 })</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule JensenDevice do
def task, do: sum( 1, 100, fn i -> 1 / i end )
Line 465 ⟶ 870:
end
 
IO.puts JensenDevice.task</langsyntaxhighlight>
 
{{out}}
<pre>
5.1873775176396215
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun sum = real by int lo, int hi, fun term
real temp = 0.0
for int i = lo; i <= hi; ++i do temp += term(i) end
return temp
end
writeLine(sum(1, 100, real by int i do return 1.0/i end))
</syntaxhighlight>
{{out}}
<pre>
5.1873775176396202608051176755
</pre>
 
Line 475 ⟶ 894:
No call by name, no macros, so I use a fun(ction). Actually, the the macro part is a lie. Somebody else, that knows how, could do a parse transform.
 
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( jensens_device ).
 
Line 487 ⟶ 906:
Temp = Term( I ),
Temp + sum( I + 1, High, Term ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 493 ⟶ 912:
4> jensens_device:task().
5.1873775176396215
</pre>
 
=={{header|Euler}}==
{{Trans|ALGOL 60}}
'''begin'''
'''new''' i; '''new''' sum;
sum &lt;- ` '''formal''' i; '''formal''' lo; '''formal''' hi; '''formal''' term;
'''begin'''
'''new''' temp; '''label''' loop;
temp &lt;- 0;
i &lt;- lo;
loop: '''begin'''
temp &lt;- temp + term;
'''if''' [ i &lt;- i + 1 ] &lt;= hi '''then''' '''goto''' loop '''else''' 0
'''end''';
temp
'''end'''
&apos;;
'''out''' sum( @i, 1, 100, `1/i&apos; )
'''end''' $
{{out}}
<pre>
NUMBER 5.1873775176
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
printfn "%.14f" (List.fold(fun n g->n+1.0/g) 0.0 [1.0..100.0]);;
</syntaxhighlight>
</lang>
{{out}}
<pre>
5.18737751763962
</pre>
 
=={{header|Factor}}==
Similar to the Java and Kotlin examples:
<langsyntaxhighlight lang="factor">: sum ( lo hi term -- x ) [ [a,b] ] dip map-sum ; inline
 
1 100 [ recip ] sum .</langsyntaxhighlight>
 
This version is a bit closer to the original, as it increments <code>i</code> in the caller's namespace.
<langsyntaxhighlight lang="factor">SYMBOL: i
 
: sum ( i lo hi term -- x )
Line 516 ⟶ 960:
inline
 
i 1 100 [ recip ] sum .</langsyntaxhighlight>
{{out}}
<pre>
Line 525 ⟶ 969:
This version passes i on the stack:
 
<langsyntaxhighlight lang="forth">: sum 0 s>f 1+ swap ?do i over execute f+ loop drop ;
:noname s>f 1 s>f fswap f/ ; 1 100 sum f.</langsyntaxhighlight>
Output: 5.18737751763962
 
The following version passes i and 1/i as execution tokens and is thus closer to the original, but less idiomatic:
 
<syntaxhighlight lang ="forth">fvariable: iisum \( i-xt is alo Forthhi wordterm-xt that-- wer need)
\ stack effects: sumi-xt ( xt1-- loaddr hi); xt2term-xt ( -- rr1 )
0e swap 1+ rot ?do ( addrr1 xtxt1 r1xt2 )
i s>f2 overpick execute f! dup execute f+
loop 2drop ;
 
' ii 1 100 :noname 1e ii f@ f/ ; sum f.</lang>
variable i1 \ avoid conflict with Forth word I
' i1 1 100 :noname 1e i1 @ s>f f/ ; sum f.</syntaxhighlight>
 
Inspired by the macro-based versions here's a more idiomatic approach that is closer to the original than the first version above (Forth-2012 code):
 
<syntaxhighlight lang="forth">: sum< ( run-time: hi+1 lo -- 0e )
0e0 postpone fliteral postpone ?do ; immediate
 
: >sum ( run-time: r1 r2 -- r3 )
postpone f+ postpone loop ; immediate
 
: main ( -- )
101 1 sum< 1e0 i s>f f/ >sum f. ;
main</syntaxhighlight>
 
This splits <code>sum</code> in two macros: <code>sum&lt;</code> and <code>&gt;sum</code>; in <code>main</code> these two words surround the code corresponding to <code>1/i</code> in the Algol 60 version. The loop limits are <code>101 1</code>, passed on the stack to <code>sum&lt;</code> in the order and semantics (upper bound is excluded) idiomatic in Forth.
 
Concerning the <code>i</code> parameter of the Algol 60 version, that is an artifact of the role of variables for storing data and passing it around in Algol-family languages. Forth's counted loops can access the current loop counter of the innermost loop with <code>i</code> (which is not a variable) without setting a variable, and that is also what one uses inside <code>sum&lt;</code> ... <code>&gt;sum</code>, as shown in <code>main</code>.
 
=={{header|Fortran}}==
Fortran does not offer call-by-name in the manner of the Algol language. It passes parameters by reference (i.e. by passing the storage address) and alternatively uses copy-in, copy-out to give the same effect, approximately, as by reference. If a parameter is an arithmetic expression, it will be evaluated and its value stored in a temporary storage area, whose address will be passed to the routine. This evaluation is done once only for each call, thus vitiating the repeated re-evaluation required by Jensen's device every time within the routine that the parameter is accessed. So, this will ''not'' work<langsyntaxhighlight Fortranlang="fortran"> FUNCTION SUM(I,LO,HI,TERM)
SUM = 0
DO I = LO,HI
Line 546 ⟶ 1,008:
END FUNCTION SUM
WRITE (6,*) SUM(I,1,100,1.0/I)
END</langsyntaxhighlight>
Here, type declarations have been omitted to save space because they won't help - until there appears a "BY NAME" or some such phrasing. Although variable <code>I</code> in the calling routine will have its value adjusted as the DO-loop in SUM proceeds (the parameter being passed by reference), this won't affect the evaluation of 1.0/I, which will be performed once using whatever value is in the caller's variable (it is uninitialised, indeed, undeclared also and so by default an integer) then the function is invoked with the address of the location containing that result. The function will make many references to that result, obtaining the same value each time. The fact that the caller's <code>I</code> will be changed each time doesn't matter.
 
Fortran does offer a facility to pass a function as a parameter using the EXTERNAL declaration, as follows - SUM is a F90 library function, so a name change to SUMJ: <langsyntaxhighlight Fortranlang="fortran"> FUNCTION SUMJ(I,LO,HI,TERM) !Attempt to follow Jensen's Device...
INTEGER I !Being by reference is workable.
INTEGER LO,HI !Just as any other parameters.
Line 569 ⟶ 1,031:
 
WRITE (6,*) SUMJ(I,1,100,THIS) !No statement as to the parameters of THIS.
END</langsyntaxhighlight>
The result of this is 5.187378, however it does not follow the formalism of Jensen's Device. The invocation statement SUMJ(I,1,100,THIS) does not contain the form of the function but only its name, and the function itself is defined separately. This means that the convenience of different functions via the likes of SUM(I,1,100,1.0/I**2) is unavailable, a separately-defined function with its own name must be defined for each such function. Further, the SUM routine must invoke TERM(I) itself, explicitly supplying the appropriate parameter. And the fact that variable <code>I</code> is a parameter to SUM is an irrelevance, and might as well be omitted from SUMJ.
 
Line 575 ⟶ 1,037:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 591 ⟶ 1,053:
func main() {
fmt.Printf("%f\n", sum(&i, 1, 100, func() float64 { return 1.0 / float64(i) }))
}</langsyntaxhighlight>
 
{{out}}
Line 601 ⟶ 1,063:
{{trans|JavaScript}}
Solution:
<langsyntaxhighlight lang="groovy">def sum = { i, lo, hi, term ->
(lo..hi).sum { i.value = it; term() }
}
def obj = [:]
println (sum(obj, 1, 100, { 1 / obj.value }))</langsyntaxhighlight>
 
Output:
Line 611 ⟶ 1,073:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad.ST
import Data.STRef
 
sum_ :: STRef s Double -> Double -> Double -> ST s Double -> ST s Double
-> ST s Double -> ST s Double
sum_ ref_i lo hi term = sum <$> mapM ((>> term) . writeSTRef ref_i) [lo .. hi]
sum_ ref lo hi term =
do
vs <- forM [lo .. hi]
(\k -> do { writeSTRef ref k
; term } )
return $ sum vs
 
foo :: Double
foo =
runST $
do iref <- newSTRef undefined -- initial value doesn't matter
sum_ i 1 100 $ recip-- <$>initial readSTRefvalue idoesn't matter
sum_ ref 1 100 $
do
k <- readSTRef ref
return $ recip k
 
main :: IO ()
main = print foo</langsyntaxhighlight>
{{Out}}
<pre>5.187377517639621</pre>
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">harmonic_sum( i, lo, hi, term ) {
temp = 0.0;
i *= 0.0;
Line 643 ⟶ 1,115:
i = 0.0;
print( "{}\n".format( harmonic_sum( i, 1.0, 100.0, @[i](){ 1.0 / i; } ) ) );
}</langsyntaxhighlight>
{{Output}}<pre>5.18737751764</pre>
 
Line 649 ⟶ 1,121:
Traditional call by name and reference are not features of Icon/Unicon. Procedures parameters are passed by value (immutable types) and reference (mutable types). However, a similar effect may be accomplished by means of co-expressions. The example below was selected for cleanliness of calling.
 
<langsyntaxhighlight Iconlang="icon">record mutable(value) # record wrapper to provide mutable access to immutable types
 
procedure main()
Line 661 ⟶ 1,133:
temp +:= @^term
return temp
end</langsyntaxhighlight>
 
Refreshing the co-expression above is more expensive to process but to avoid it requires unary alternation in the call.
<langsyntaxhighlight Iconlang="icon"> write( sum(A, 1, 100, create |1.0/A.value) )
...
temp +:= @term</langsyntaxhighlight>
 
Alternately, we can use a programmer defined control operator (PDCO) approach that passes every argument as a co-expression. Again the refresh co-expression/unary iteration trade-off can be made. The call is cleaner looking but the procedure code is less clear. Additionally all the parameters are passed as individual co-expressions.
<langsyntaxhighlight Iconlang="icon"> write( sum{A.value, 1, 100, 1.0/A.value} )
...
procedure sum(X)
...
every @X[1] := @X[2] to @X[3] do
temp +:= @^X[4]</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">jensen=: monad define
'name lo hi expression'=. y
temp=. 0
Line 685 ⟶ 1,157:
temp=. temp + ".expression
end.
)</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="j"> jensen 'i';1;100;'1%i'
5.18738</langsyntaxhighlight>
 
Note, however, that in J it is reasonably likely that the expression (or an obvious variation on the expression) can deal with the looping itself. And in typical use this often simplifies to entering the expression and data directly on the command line.
Line 697 ⟶ 1,169:
This is Java 8.
 
<langsyntaxhighlight lang="java">import java.util.function.*;
import java.util.stream.*;
 
Line 709 ⟶ 1,181:
}
}
</syntaxhighlight>
</lang>
The program prints '5.187377517639621'.
 
Java 7 is more verbose, but under the hood does essentially the same thing:
 
<langsyntaxhighlight lang="java">public class Jensen2 {
 
interface IntToDoubleFunction {
Line 735 ⟶ 1,207:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
Line 742 ⟶ 1,214:
Uses an object ''o'' instead of integer pointer ''i'', as the C example does.
 
<langsyntaxhighlight lang="javascript">var obj;
 
function sum(o, lo, hi, term) {
Line 752 ⟶ 1,224:
 
obj = {val: 0};
alert(sum(obj, 1, 100, function() {return 1 / obj.val}));</langsyntaxhighlight>
The alert shows us '5.187377517639621'.
 
=={{header|Joy}}==
<langsyntaxhighlight Joylang="joy">100 [0] [[1.0 swap /] dip +] primrec.</langsyntaxhighlight>
Joy does not have named parameters.
Neither i nor 1/i are visible in the program.
Line 762 ⟶ 1,234:
=={{header|jq}}==
The technique used in the Javascript example can also be used in jq, but in jq it is more idiomatic to use "." to refer to the current term. For example, using sum/3 defined below, we can write: sum(1; 100; 1/.) to perform the task.
<langsyntaxhighlight lang="jq">def sum(lo; hi; term):
reduce range(lo; hi+1) as $i (0; . + ($i|term));
 
# The task:
sum(1;100;1/.)</langsyntaxhighlight>
{{Out}}
$ jq -n -f jensen.jq
Line 775 ⟶ 1,247:
{{trans|C}}
 
<langsyntaxhighlight lang="julia">macro sum(i, loname, hiname, term)
return quote
lo = $loname
Line 788 ⟶ 1,260:
 
i = 0
@sum(i, 1, 100, 1.0 / i)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">fun sum(lo: Int, hi: Int, f: (Int) -> Double) = (lo..hi).sumByDouble(f)
 
fun main(args: Array<String>) = println(sum(1, 100, { 1.0 / it }))</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def jensen
{lambda {:n}
{+ {S.map {lambda {:i} {/ 1 :i}}
{S.serie 1 :n}} }}}
-> jensen
 
{jensen 100}
-> 5.187377517639621
</syntaxhighlight>
I probably didn't understand this task, what's going on ...
 
=={{header|Lua}}==
 
<syntaxhighlight lang="lua">
<lang Lua>
function sum(var, a, b, str)
local ret = 0
Line 806 ⟶ 1,291:
end
print(sum("i", 1, 100, "1/i"))
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
The definition of the lazy function has two statements. First statement is a Module with one argument, the actual name of Jensen`s_Device, which make the function to get the same scope as module Jensen`s_Device, and the second statement is =1/i which return the expression.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Jensen`s_Device {
Def double i
Line 826 ⟶ 1,311:
}
Jensen`s_Device
</syntaxhighlight>
</lang>
 
Using Decimal for better accuracy. change &i to &any to show that: when any change, change i, so f() use this i.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Jensen`s_Device {
Def decimal i
Line 843 ⟶ 1,328:
}
Jensen`s_Device
</syntaxhighlight>
</lang>
 
Many other examples use single float. So this is one for single.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Jensen`s_Device {
Def single i
Line 860 ⟶ 1,345:
}
Jensen`s_Device
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
Line 870 ⟶ 1,355:
`pushdef(`temp',0)`'for(`$1',$2,$3,
`define(`temp',eval(temp+$4))')`'temp`'popdef(`temp')')
sum(`i',1,100,`1000/i')</langsyntaxhighlight>
 
Output:
Line 879 ⟶ 1,364:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
 
<langsyntaxhighlight Mathematicalang="mathematica">sum[term_, i_, lo_, hi_] := Block[{temp = 0},
Do[temp = temp + term, {i, lo, hi}];
temp];
SetAttributes[sum, HoldFirst];</langsyntaxhighlight>
 
Output:
Line 893 ⟶ 1,378:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">mysum(e, v, lo, hi) := block([s: 0], for i from lo thru hi do s: s + subst(v=i, e), s)$
 
mysum(1/n, n, 1, 10);
Line 907 ⟶ 1,392:
/* still works */
mysum(1/n, n, 1, 10);
7381/2520</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">
import COM.ibm.netrexx.process.
 
Line 948 ⟶ 1,433:
return Rexx termMethod.invoke(null,[iv])
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">var i: int
 
proc harmonicSum(i: var int,; lo, hi,: int; term: proc: float): float =
i = lo
while i <= hi:
Line 959 ⟶ 1,444:
inc i
 
echo harmonicSum(i, 1, 100, proc: float = 1.0 / float(i))</langsyntaxhighlight>
 
Output:
{{out}}
<pre>5.1873775176396206e+00</pre>
<pre>5.5.187377517639621</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Jensens {
Line 988 ⟶ 1,474:
}
}
</syntaxhighlight>
</lang>
 
Output: 5.18738
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let i = ref 42 (* initial value doesn't matter *)
 
let sum' i lo hi term =
Line 1,005 ⟶ 1,491:
 
let () =
Printf.printf "%f\n" (sum' i 1 100 (fun () -> 1. /. float !i))</langsyntaxhighlight>
Output: 5.187378
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: mysum(lo, hi, term) | i | 0 lo hi for: i [ i term perform + ] ;</langsyntaxhighlight>
 
{{out}}
Line 1,023 ⟶ 1,509:
=={{header|Oz}}==
Translation using mutable references and an anonymous function:
<langsyntaxhighlight lang="oz">declare
fun {Sum I Lo Hi Term}
Temp = {NewCell 0.0}
Line 1,036 ⟶ 1,522:
I = {NewCell unit}
in
{Show {Sum I 1 100 fun {$} 1.0 / {Int.toFloat @I} end}}</langsyntaxhighlight>
 
Idiomatic code:
<langsyntaxhighlight lang="oz">declare
fun {Sum Lo Hi F}
{FoldL {Map {List.number Lo Hi 1} F} Number.'+' 0.0}
end
in
{Show {Sum 1 100 fun {$ I} 1.0/{Int.toFloat I} end}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 1,050 ⟶ 1,536:
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">program Jensens_Device;
<lang pascal>{$MODE objFPC}
 
{$IFDEF FPC}
{$MODE objFPC}
{$ENDIF}
 
type
tTerm = function(i: integer): real;
 
function term(i: integer): real;
begin
Begin
term := 1 / i;
end;
 
function sum(var i: LongInt; lo, hi: integer; term: tTerm): real;
begin
lo,hi: integer;
term:tTerm):real;
Begin
result := 0;
i := lo;
while i <= hi do begin
begin
result := result+term(i);
result := result + term(i);
inc(i);
end;
end;
 
var
i : LongInt;
 
Begin
begin
writeln(sum(i,1,100,@term));
writeln(sum(i, 1, 100, @term));
end.
{$IFNDEF UNIX} readln; {$ENDIF}
</lang>
end.</syntaxhighlight>
Out
<pre> 5.1873775176396206E+000</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $i;
sub sum {
my ($i, $lo, $hi, $term) = @_;
Line 1,092 ⟶ 1,582:
}
 
print sum(\$i, 1, 100, sub { 1 / $i }), "\n";</langsyntaxhighlight>
Output: 5.18737751763962
 
Or you can take advantage of the fact that elements of the @_ are aliases of the original:
<langsyntaxhighlight lang="perl">my $i;
sub sum {
my (undef, $lo, $hi, $term) = @_;
Line 1,106 ⟶ 1,596:
}
 
print sum($i, 1, 100, sub { 1 / $i }), "\n";</langsyntaxhighlight>
Output: 5.18737751763962
 
Line 1,113 ⟶ 1,603:
I could also have done what C and PHP are doing, though in Phix I'd have to explicitly assign the static var within the loop.<br>
I wholeheartedly agree with the comment on the Clipper example.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function sumr(integer lo, hi, rid)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
atom res = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">sumr</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">lo</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">)</span>
for i=lo to hi do
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
res += call_func(rid,{i})
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">lo</span> <span style="color: #008080;">to</span> <span style="color: #000000;">hi</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">res</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
return res
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function reciprocal(atom i) return 1/i end function
<span style="color: #008080;">function</span> <span style="color: #000000;">reciprocal</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">i</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?sumr(1, 100, routine_id("reciprocal"))</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">sumr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">reciprocal</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,130 ⟶ 1,623:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">$i;
function sum (&$i, $lo, $hi, $term) {
$temp = 0;
Line 1,154 ⟶ 1,647:
 
//Output: 5.1873775176396
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 6)
 
(de jensen (I Lo Hi Term)
Line 1,170 ⟶ 1,663:
(format
(jensen I 1 100 '(() (*/ 1.0 (val I))))
*Scl ) )</langsyntaxhighlight>
Output:
<pre>-> "5.187383"</pre>
 
=={{header|PureBasic}}==
{{trans|C}}
<lang PureBasic>Prototype.d func()
 
Global i
 
Procedure.d Sum(*i.Integer, lo, hi, *term.func)
Protected Temp.d
For i=lo To hi
temp + *term()
Next
ProcedureReturn Temp
EndProcedure
 
Procedure.d term_func()
ProcedureReturn 1/i
EndProcedure
 
Answer.d = Sum(@i, 1, 100, @term_func())</lang>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">class Ref(object):
def __init__(self, value=None):
self.value = value
Line 1,212 ⟶ 1,685:
# 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 harmonic_sum(i, 1, 100, lambda: 1.0/i.value)</langsyntaxhighlight>
 
or
 
<langsyntaxhighlight lang="python">
def harmonic_sum(i, lo, hi, term):
return sum(term() for i[0] in range(lo, hi + 1))
Line 1,222 ⟶ 1,695:
i = [0]
print(harmonic_sum(i, 1, 100, lambda: 1.0 / i[0]))
</syntaxhighlight>
</lang>
 
or
 
<langsyntaxhighlight lang="python">
def harmonic_sum(i, lo, hi, term):
return sum(eval(term) for i[0] in range(lo, hi + 1))
Line 1,232 ⟶ 1,705:
i = [0]
print(harmonic_sum(i, 1, 100, "1.0 / i[0]"))
</syntaxhighlight>
</lang>
 
Output: 5.18737751764
Line 1,242 ⟶ 1,715:
of a function; however, ignoring conventions we can come disturbingly close to the ALGOL call-by-name semantics.
 
<langsyntaxhighlight Rlang="r">sum <- function(var, lo, hi, term)
eval(substitute({
.temp <- 0;
Line 1,256 ⟶ 1,729:
##and because of enclos=parent.frame(), the term can involve variables in the caller's scope:
x <- -1
sum(i, 1, 100, i^x) #5.187378</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,262 ⟶ 1,735:
be written just as Jørn Jensen did at Regnecentralen.
 
<langsyntaxhighlight lang="racket">
#lang algol60
begin
Line 1,281 ⟶ 1,754:
printnln (sum (i, 1, 100, 1/i))
end
</syntaxhighlight>
</lang>
 
But of course you can also use the more boring popular alternative of first class functions:
 
<langsyntaxhighlight lang="racket">
#lang racket/base
(define (sum lo hi f)
(for/sum ([i (in-range lo (add1 hi))]) (f i)))
(sum 1 100 (λ(i) (/ 1.0 i)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,296 ⟶ 1,769:
 
Rather than playing tricks like Perl&nbsp;5 does, the declarations of the formal parameters are quite straightforward in Raku:
<syntaxhighlight lang="raku" perl6line>sub sum($i is rw, $lo, $hi, &term) {
my $temp = 0;
loop ($i = $lo; $i <= $hi; $i++) {
Line 1,305 ⟶ 1,778:
 
my $i;
say sum $i, 1, 100, { 1 / $i };</langsyntaxhighlight>
Note that the C-style "for" loop is pronounced "loop" in Raku, and is the only loop statement that actually requires parens.
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">public num Jenssen(int lo, int hi, num (int i) term){
temp = 0;
while (lo <= hi){
Line 1,315 ⟶ 1,788:
lo += 1;}
return temp;
}</langsyntaxhighlight>
 
With as output:
 
<langsyntaxhighlight lang="rascal">rascal>Jenssen(1, 100, num(int i){return 1.0/i;})
num: 5.18737751763962026080511767565825315790897212670845165317653395662</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates Jensen's device (via call subroutine, and args by name). */
parse arg d . /*obtain optional argument from the CL.*/
if d=='' | d=="," then d= 100 /*Not specified? Then use the default.*/
Line 1,339 ⟶ 1,812:
/*comment lit var lit var lit var literal var literal */
 
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,360 ⟶ 1,833:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Jensen's Device
 
Line 1,374 ⟶ 1,847:
next
return temp
</syntaxhighlight>
</lang>
Output:
<pre>
5.18737751763962
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ → idx lo hi term
≪ lo idx STO 0
DO
term EVAL +
1 idx STO+
UNTIL idx EVAL hi > END
idx PURGE
‘SUM’ STO
'K' 1 100 '1/K' SUM
'N' 0 100 '1/FACT(N)' SUM
{{out}}
<pre>
2: 5.18737751764
1: 2.71828182846
</pre>
 
=={{header|Ruby}}==
Here, setting the variable and evaluating the term are truly executed in the "outer" context:
<langsyntaxhighlight lang="ruby">def sum(var, lo, hi, term, context)
sum = 0.0
lo.upto(hi) do |n|
Line 1,389 ⟶ 1,883:
sum
end
p sum "i", 1, 100, "1.0 / i", binding # => 5.18737751763962</langsyntaxhighlight>
 
But here is the Ruby way to do it:
<langsyntaxhighlight lang="ruby">def sum2(lo, hi)
lo.upto(hi).inject(0.0) {|sum, n| sum += yield n}
end
p sum2(1, 100) {|i| 1.0/i} # => 5.18737751763962</langsyntaxhighlight>
 
Even more concise: (requires ruby >= 2.4)
<langsyntaxhighlight lang="ruby">
def sum lo, hi, &term
(lo..hi).sum(&term)
Line 1,405 ⟶ 1,899:
# or using Rational:
p sum(1,100){|i| Rational(1,i)} # => 14466636279520351160221518043104131447711 / 2788815009188499086581352357412492142272
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use std::f32;
 
fn harmonic_sum<F>(lo: usize, hi: usize, term: F) -> f32
where
F: Fn(f32) -> f32,
{
(lo..hi + 1).fold(0.0, |acc, item| acc + term(item as f32))
}
 
fn main() {
println!("{}", harmonic_sum(1, 100, |i| 1.0 / i));
}
 
</syntaxhighlight>
{{out}}
<pre>
5.187378
</pre>
 
=={{header|Scala}}==
Line 1,414 ⟶ 1,929:
class, which is effectively the same as passing by reference.
 
<langsyntaxhighlight lang="scala">class MyInt { var i: Int = _ }
val i = new MyInt
def sum(i: MyInt, lo: Int, hi: Int, term: => Double) = {
Line 1,425 ⟶ 1,940:
temp
}
sum(i, 1, 100, 1.0 / i.i)</langsyntaxhighlight>
 
Result:
Line 1,436 ⟶ 1,951:
Scheme procedures do not support call-by-name. Scheme macros, however, do:
 
<langsyntaxhighlight lang="scheme">
(define-syntax sum
(syntax-rules ()
Line 1,446 ⟶ 1,961:
(loop (+ var 1)
(+ result . body)))))))
</syntaxhighlight>
</lang>
 
<pre>
Line 1,456 ⟶ 1,971:
Seed7 supports call-by-name with function parameters:
 
<langsyntaxhighlight lang="seed7">
$ include "seed7_05.s7i";
include "float.s7i";
Line 1,476 ⟶ 1,991:
writeln(sum(i, 1, 100, 1.0/flt(i)) digits 6);
end func;
</syntaxhighlight>
</lang>
 
Output:
Line 1,484 ⟶ 1,999:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var i;
func sum (i, lo, hi, term) {
var temp = 0;
for (*i = lo; *i <= hi; (*i)++) {
temp += term.run;
};
return temp;
};
say sum(\i, 1, 100, { 1 / i });</langsyntaxhighlight>
{{out}}
<pre>5.1873775176396202608051176756582531579089918737751763962026080511767565825315790897212671</pre>
 
=={{header|Simula}}==
{{trans|algol60}}
{{works with|SIMULA-67}}
Compare with Algol 60, in Simula 67 'call by name' is specified with '''name'''. It is a true 'call by name' evaluation not a 'procedure parameter' emulation.<langsyntaxhighlight lang="simula">comment Jensen's Device;
begin
integer i;
Line 1,521 ⟶ 2,036:
comment note the correspondence between the mathematical notation and the call to sum;
outreal (sum (i, 1, 100, 1/i), 7, 14)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 1,528 ⟶ 2,043:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">val i = ref 42 (* initial value doesn't matter *)
 
fun sum' (i, lo, hi, term) = let
Line 1,542 ⟶ 2,057:
 
val () =
print (Real.toString (sum' (i, 1, 100, fn () => 1.0 / real (!i))) ^ "\n")</langsyntaxhighlight>
Output: 5.18737751764
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var i = 42 // initial value doesn't matter
 
func sum(inout i: Int, lo: Int, hi: Int, @autoclosure term: () -> Double) -> Double {
Line 1,556 ⟶ 2,071:
}
 
println(sum(&i, 1, 100, 1 / Double(i)))</langsyntaxhighlight>
(Prior to Swift 1.2, replace <code>@autoclosure term: () -> Double</code> with <code>term: @autoclosure () -> Double</code>.)
{{out}}
Line 1,563 ⟶ 2,078:
=={{header|Tcl}}==
Here, we set the value of the passed variable in the caller's frame. We then evaluate the passed term there too.
<langsyntaxhighlight lang="tcl">proc sum {var lo hi term} {
upvar 1 $var x
set sum 0.0
Line 1,571 ⟶ 2,086:
return $sum
}
puts [sum i 1 100 {1.0/$i}] ;# 5.177377517639621</langsyntaxhighlight>
However, the solution is expressed more simply like this
<langsyntaxhighlight lang="tcl">proc sum2 {lo hi lambda} {
set sum 0.0
for {set n $lo} {$n < $hi} {incr n} {
Line 1,580 ⟶ 2,095:
return $sum
}
puts [sum2 1 100 {i {expr {1.0/$i}}}] ;# 5.177377517639621</langsyntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Private Function sum(i As String, ByVal lo As Integer, ByVal hi As Integer, term As String) As Double
Dim temp As Double
Line 1,596 ⟶ 2,111:
Debug.Print sum("j", 1, 100, "sin(j)")
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,606 ⟶ 2,121:
=={{header|Wren}}==
As Wren doesn't support call by name, call by reference nor pointers we need to 'box' the global numeric variable 'i' and use a function for 'term' to simulate Jensen's device. This works because all user defined types are reference types and functions can capture external variables.
<langsyntaxhighlight ecmascriptlang="wren">class Box {
construct new(v) { _v = v }
v { _v }
Line 1,625 ⟶ 2,140:
 
var s = sum.call(i, 1, 100, Fn.new { 1/i.v })
System.print(s)</langsyntaxhighlight>
 
{{out}}
Line 1,634 ⟶ 2,149:
=={{header|zkl}}==
zkl doesn't support call by name/address but does have reference objects. Using an explicit call to term:
<langsyntaxhighlight lang="zkl">fcn sum(ri, lo,hi, term){
temp:=0.0; ri.set(lo);
do{ temp+=term(ri); } while(ri.inc()<hi); // inc return previous value
return(temp);
}
sum(Ref(0), 1,100, fcn(ri){ 1.0/ri.value }).println();</langsyntaxhighlight>
Using function application/deferred(lazy) objects, we can make the function call implicit (addition forces evaluation of the LHS):
<langsyntaxhighlight lang="zkl">fcn sum2(ri, lo,hi, term){
temp:=0.0; ri.set(lo);
do{ temp=term + temp; } while(ri.inc()<hi); // inc return previous value
Line 1,647 ⟶ 2,162:
}
ri:=Ref(0);
sum2(ri, 1,100, 'wrap(){ 1.0/ri.value }).println();</langsyntaxhighlight>
In this case, we can call sum or sum2 and it does the same thing (the ri parameter will be ignored).
 
Of course, as others have pointed out, this can be expressed very simply:
<langsyntaxhighlight lang="zkl">fcn sum3(lo,hi, term){ [lo..hi].reduce('wrap(sum,i){ sum + term(i) },0.0) }
sum3(1,100, fcn(i){ 1.0/i }).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,658 ⟶ 2,173:
5.187378
5.187378
</pre>
 
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>10 DEF FN r(x)=1/x
20 LET f$="FN r(i)"
30 LET lo=1: LET hi=100
40 GO SUB 1000
50 PRINT temp
60 STOP
1000 REM Evaluation
1010 LET temp=0
1020 FOR i=lo TO hi
1030 LET temp=temp+VAL f$
1040 NEXT i
1050 RETURN
</lang>
{{out}}
<pre>
5.1873775
</pre>
 
2,122

edits