Jensen's Device: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Joy}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 36:
{{trans|C#}}
<
V temp = 0.0
i = lo
Line 48:
print(sum(&i, 1, 100, () -> 1 / @i))
main()</
{{out}}
Line 56:
=={{header|Ada}}==
<
procedure Jensen_Device is
Line 81:
begin
Put_Line (Float'Image (Sum (I'Access, 1.0, 100.0, Inv_I'Access)));
end Jensen_Device;</
<pre>
5.18738E+00
Line 108:
=={{header|ALGOL 68}}==
{{trans|ALGOL 60}}
<
INT i;
PROC sum = (REF INT i, INT lo, hi, PROC REAL term)REAL:
Line 123:
COMMENT note the correspondence between the mathematical notation and the call to sum COMMENT
print (sum (i, 1, 100, REAL: 1/i))
END</
Output: +5.18737751763962e +0
Line 131:
<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.
<
integer i;
real procedure sum ( integer %name% i; integer value lo, hi; real procedure term );
Line 147:
% note the correspondence between the mathematical notation and the call to sum %
write( sum( i, 1, 100, 1/i ) )
end.</
{{out}}
<pre>
Line 153:
=={{header|AppleScript}}==
<
on jsum(i, lo, hi, term)
Line 169:
end script
return jsum(a reference to i, 1, 100, term_func)</
Output: 5.18737751764
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 259:
fUn: .float 1
</syntaxhighlight>
=={{header|Arturo}}==
{{trans|Ruby}}
<
result: new 0.0
loop lo..hi 'n ->
Line 268:
result
]
print ["harmonicSum 1->100:" harmonicSum 'i 1 100 {1.0 / i}]</
{{out}}
Line 275:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f JENSENS_DEVICE.AWK
# converted from FreeBASIC
Line 290:
printf("%.15f\n",tmp)
}
</syntaxhighlight>
{{out}}
<pre>
Line 298:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<
lo = 1 : hi = 100 : temp = 0
for i = lo to hi
Line 307:
call Evaluation()
end</
{{out}}
<pre>
Line 316:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
END
Line 326:
= temp
DEF FNreciprocal = 1/i</
Output:
<pre>
Line 333:
=={{header|Bracmat}}==
<
= I lo hi Term temp
. !arg:((=?I),?lo,?hi,(=?Term))
Line 346:
)
& sum$((=i),1,100,(=!i^-1))
);</
Output:
<pre>14466636279520351160221518043104131447711/2788815009188499086581352357412492142272</pre>
=={{header|C}}==
<
int i;
Line 366:
printf("%f\n", sum(&i, 1, 100, term_func));
return 0;
}</
Output: 5.18738
{{works with|gcc}}
Alternatively, C's macros provide a closer imitation of ALGOL's call-by-name semantics:
<
int i;
Line 389:
printf("%f\n", sum(i, 1, 100, 1.0 / i));
return 0;
}</
Output: 5.187378
=={{header|C sharp}}==
Can be simulated via lambda expressions:
<
class JensensDevice
Line 413:
Console.WriteLine(Sum(ref i, 1, 100, () => 1.0 / i));
}
}</
=={{header|C++}}==
<
#include <iostream>
Line 439:
std::cout << SUM(i,1,100,1.0/i) << "\n";
return 0;
}</
Output: 5.18738
5.18738
Line 445:
=={{header|Clipper}}==
With hindsight Algol60 provided this feature in a way that is terrible for program maintenance, because the calling code looks innocuous.
<
// A fairly direct translation of the Algol 60
// John M Skelton 11-Feb-2012
Line 465:
next i
return temp
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 471:
Common Lisp does not have call-by-name for functions; however, it can be directly simulated by a macro wrapping selected parameters in lambdas.
<
(defun %sum (lo hi func)
Line 477:
(defmacro sum (i lo hi term)
`(%sum ,lo ,hi (lambda (,i) ,term)))</
<
14466636279520351160221518043104131447711/2788815009188499086581352357412492142272
CL-USER> (float (sum i 1 100 (/ 1 i)))
5.1873775</
=={{header|D}}==
There are better ways to do this in D, but this is closer to the original Algol version:
<
pure @safe /*nothrow @nogc*/ {
double result = 0.0;
Line 499:
int i;
sum(i, 1, 100, 1.0/i).writeln;
}</
{{out}}
<pre>
Line 506:
=={{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.
<
begin
i:=lo;
Line 517:
var i : Integer;
PrintLn(sum(i, 1, 100, 1.0/i));</
Output: 5.187...
Line 526:
(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>.)
<
def sum(&i, lo, hi, &term) { # bind i and term to passed slots
var temp := 0
Line 539:
var i := null
sum(&i, 1, 100, def _.get() { return 1/i })
}</
<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 547:
This emulation of the original call-by-name is of course unidiomatic; a natural version of the same computation would be:
<
var temp := 0
for i in lo..hi { temp += f(i) }
return temp
}
sum(1, 100, fn i { 1/i })</
=={{header|Elixir}}==
{{trans|Erlang}}
<
def task, do: sum( 1, 100, fn i -> 1 / i end )
Line 566:
end
IO.puts JensenDevice.task</
{{out}}
Line 576:
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">
-module( jensens_device ).
Line 588:
Temp = Term( I ),
Temp + sum( I + 1, High, Term ).
</syntaxhighlight>
{{out}}
Line 597:
=={{header|F_Sharp|F#}}==
<
printfn "%.14f" (List.fold(fun n g->n+1.0/g) 0.0 [1.0..100.0]);;
</syntaxhighlight>
{{out}}
<pre>
Line 606:
=={{header|Factor}}==
Similar to the Java and Kotlin examples:
<
1 100 [ recip ] sum .</
This version is a bit closer to the original, as it increments <code>i</code> in the caller's namespace.
<
: sum ( i lo hi term -- x )
Line 617:
inline
i 1 100 [ recip ] sum .</
{{out}}
<pre>
Line 626:
This version passes i on the stack:
<
:noname s>f 1 s>f fswap f/ ; 1 100 sum f.</
Output: 5.18737751763962
The following version passes i and 1/i as execution tokens and is thus closer to the original, but less idiomatic:
<
: sum ( xt1 lo hi xt2 -- r )
0e swap 1+ rot ?do ( addr xt r1 )
i s>f over execute f! dup execute f+
loop 2drop ;
' ii 1 100 :noname 1e ii f@ f/ ; sum f.</
=={{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<
SUM = 0
DO I = LO,HI
Line 647:
END FUNCTION SUM
WRITE (6,*) SUM(I,1,100,1.0/I)
END</
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: <
INTEGER I !Being by reference is workable.
INTEGER LO,HI !Just as any other parameters.
Line 670:
WRITE (6,*) SUMJ(I,1,100,THIS) !No statement as to the parameters of THIS.
END</
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 677:
=={{header|FreeBASIC}}==
<
Dim As Integer i, lo = 1, hi = 100
Dim As Double temp = 0
Line 687:
Evaluation
Sleep</
{{out}}
<pre>
Line 695:
=={{header|Go}}==
<
import "fmt"
Line 711:
func main() {
fmt.Printf("%f\n", sum(&i, 1, 100, func() float64 { return 1.0 / float64(i) }))
}</
{{out}}
Line 721:
{{trans|JavaScript}}
Solution:
<
(lo..hi).sum { i.value = it; term() }
}
def obj = [:]
println (sum(obj, 1, 100, { 1 / obj.value }))</
Output:
Line 731:
=={{header|Haskell}}==
<
import Data.STRef
Line 744:
main :: IO ()
main = print foo</
{{Out}}
<pre>5.187377517639621</pre>
=={{header|Huginn}}==
<
temp = 0.0;
i *= 0.0;
Line 763:
i = 0.0;
print( "{}\n".format( harmonic_sum( i, 1.0, 100.0, @[i](){ 1.0 / i; } ) ) );
}</
{{Output}}<pre>5.18737751764</pre>
Line 769:
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.
<
procedure main()
Line 781:
temp +:= @^term
return temp
end</
Refreshing the co-expression above is more expensive to process but to avoid it requires unary alternation in the call.
<
...
temp +:= @term</
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.
<
...
procedure sum(X)
...
every @X[1] := @X[2] to @X[3] do
temp +:= @^X[4]</
=={{header|J}}==
'''Solution:'''
<
'name lo hi expression'=. y
temp=. 0
Line 805:
temp=. temp + ".expression
end.
)</
'''Example:'''
<
5.18738</
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 817:
This is Java 8.
<
import java.util.stream.*;
Line 829:
}
}
</syntaxhighlight>
The program prints '5.187377517639621'.
Java 7 is more verbose, but under the hood does essentially the same thing:
<
interface IntToDoubleFunction {
Line 855:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 862:
Uses an object ''o'' instead of integer pointer ''i'', as the C example does.
<
function sum(o, lo, hi, term) {
Line 872:
obj = {val: 0};
alert(sum(obj, 1, 100, function() {return 1 / obj.val}));</
The alert shows us '5.187377517639621'.
=={{header|Joy}}==
<syntaxhighlight lang=
Joy does not have named parameters.
Neither i nor 1/i are visible in the program.
Line 882:
=={{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.
<
reduce range(lo; hi+1) as $i (0; . + ($i|term));
# The task:
sum(1;100;1/.)</
{{Out}}
$ jq -n -f jensen.jq
Line 895:
{{trans|C}}
<
return quote
lo = $loname
Line 908:
i = 0
@sum(i, 1, 100, 1.0 / i)</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) = println(sum(1, 100, { 1.0 / it }))</
=={{header|Lua}}==
<syntaxhighlight lang="lua">
function sum(var, a, b, str)
local ret = 0
Line 926:
end
print(sum("i", 1, 100, "1/i"))
</syntaxhighlight>
=={{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">
Module Jensen`s_Device {
Def double i
Line 946:
}
Jensen`s_Device
</syntaxhighlight>
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">
Module Jensen`s_Device {
Def decimal i
Line 963:
}
Jensen`s_Device
</syntaxhighlight>
Many other examples use single float. So this is one for single.
<syntaxhighlight lang="m2000 interpreter">
Module Jensen`s_Device {
Def single i
Line 980:
}
Jensen`s_Device
</syntaxhighlight>
=={{header|M4}}==
<
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
Line 990:
`pushdef(`temp',0)`'for(`$1',$2,$3,
`define(`temp',eval(temp+$4))')`'temp`'popdef(`temp')')
sum(`i',1,100,`1000/i')</
Output:
Line 999:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Do[temp = temp + term, {i, lo, hi}];
temp];
SetAttributes[sum, HoldFirst];</
Output:
Line 1,013:
=={{header|Maxima}}==
<
mysum(1/n, n, 1, 10);
Line 1,027:
/* still works */
mysum(1/n, n, 1, 10);
7381/2520</
=={{header|NetRexx}}==
<
import COM.ibm.netrexx.process.
Line 1,068:
return Rexx termMethod.invoke(null,[iv])
</syntaxhighlight>
=={{header|Nim}}==
<
proc harmonicSum(i: var int; lo, hi: int; term: proc: float): float =
Line 1,079:
inc i
echo harmonicSum(i, 1, 100, proc: float = 1 / i)</
{{out}}
Line 1,085:
=={{header|Objeck}}==
<
bundle Default {
class Jensens {
Line 1,109:
}
}
</syntaxhighlight>
Output: 5.18738
=={{header|OCaml}}==
<
let sum' i lo hi term =
Line 1,126:
let () =
Printf.printf "%f\n" (sum' i 1 100 (fun () -> 1. /. float !i))</
Output: 5.187378
=={{header|Oforth}}==
<
{{out}}
Line 1,144:
=={{header|Oz}}==
Translation using mutable references and an anonymous function:
<
fun {Sum I Lo Hi Term}
Temp = {NewCell 0.0}
Line 1,157:
I = {NewCell unit}
in
{Show {Sum I 1 100 fun {$} 1.0 / {Int.toFloat @I} end}}</
Idiomatic code:
<
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}}</
=={{header|PARI/GP}}==
Line 1,171:
=={{header|Pascal}}==
<
{$IFDEF FPC}
Line 1,202:
writeln(sum(i, 1, 100, @term));
{$IFNDEF UNIX} readln; {$ENDIF}
end.</
Out
<pre> 5.1873775176396206E+000</pre>
=={{header|Perl}}==
<
sub sum {
my ($i, $lo, $hi, $term) = @_;
Line 1,217:
}
print sum(\$i, 1, 100, sub { 1 / $i }), "\n";</
Output: 5.18737751763962
Or you can take advantage of the fact that elements of the @_ are aliases of the original:
<
sub sum {
my (undef, $lo, $hi, $term) = @_;
Line 1,231:
}
print sum($i, 1, 100, sub { 1 / $i }), "\n";</
Output: 5.18737751763962
Line 1,238:
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.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 1,251:
<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>
<!--</
{{out}}
<pre>
Line 1,258:
=={{header|PHP}}==
<
function sum (&$i, $lo, $hi, $term) {
$temp = 0;
Line 1,282:
//Output: 5.1873775176396
</syntaxhighlight>
=={{header|PicoLisp}}==
<
(de jensen (I Lo Hi Term)
Line 1,298:
(format
(jensen I 1 100 '(() (*/ 1.0 (val I))))
*Scl ) )</
Output:
<pre>-> "5.187383"</pre>
Line 1,304:
=={{header|PureBasic}}==
{{trans|C}}
<
Global i
Line 1,320:
EndProcedure
Answer.d = Sum(@i, 1, 100, @term_func())</
=={{header|Python}}==
<
def __init__(self, value=None):
self.value = value
Line 1,340:
# 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)</
or
<
def harmonic_sum(i, lo, hi, term):
return sum(term() for i[0] in range(lo, hi + 1))
Line 1,350:
i = [0]
print(harmonic_sum(i, 1, 100, lambda: 1.0 / i[0]))
</syntaxhighlight>
or
<
def harmonic_sum(i, lo, hi, term):
return sum(eval(term) for i[0] in range(lo, hi + 1))
Line 1,360:
i = [0]
print(harmonic_sum(i, 1, 100, "1.0 / i[0]"))
</syntaxhighlight>
Output: 5.18737751764
Line 1,370:
of a function; however, ignoring conventions we can come disturbingly close to the ALGOL call-by-name semantics.
<
eval(substitute({
.temp <- 0;
Line 1,384:
##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</
=={{header|Racket}}==
Line 1,390:
be written just as Jørn Jensen did at Regnecentralen.
<
#lang algol60
begin
Line 1,409:
printnln (sum (i, 1, 100, 1/i))
end
</syntaxhighlight>
But of course you can also use the more boring popular alternative of first class functions:
<
#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>
=={{header|Raku}}==
Line 1,424:
Rather than playing tricks like Perl 5 does, the declarations of the formal parameters are quite straightforward in Raku:
<syntaxhighlight lang="raku"
my $temp = 0;
loop ($i = $lo; $i <= $hi; $i++) {
Line 1,433:
my $i;
say sum $i, 1, 100, { 1 / $i };</
Note that the C-style "for" loop is pronounced "loop" in Raku, and is the only loop statement that actually requires parens.
=={{header|Rascal}}==
<
temp = 0;
while (lo <= hi){
Line 1,443:
lo += 1;}
return temp;
}</
With as output:
<
num: 5.18737751763962026080511767565825315790897212670845165317653395662</
=={{header|REXX}}==
<
parse arg d . /*obtain optional argument from the CL.*/
if d=='' | d=="," then d= 100 /*Not specified? Then use the default.*/
Line 1,467:
/*comment lit var lit var lit var literal var literal */
return $</
{{out|output|text= when using the default input:}}
<pre>
Line 1,488:
=={{header|Ring}}==
<
# Project : Jensen's Device
Line 1,502:
next
return temp
</syntaxhighlight>
Output:
<pre>
Line 1,510:
=={{header|Ruby}}==
Here, setting the variable and evaluating the term are truly executed in the "outer" context:
<
sum = 0.0
lo.upto(hi) do |n|
Line 1,517:
sum
end
p sum "i", 1, 100, "1.0 / i", binding # => 5.18737751763962</
But here is the Ruby way to do it:
<
lo.upto(hi).inject(0.0) {|sum, n| sum += yield n}
end
p sum2(1, 100) {|i| 1.0/i} # => 5.18737751763962</
Even more concise: (requires ruby >= 2.4)
<
def sum lo, hi, &term
(lo..hi).sum(&term)
Line 1,533:
# or using Rational:
p sum(1,100){|i| Rational(1,i)} # => 14466636279520351160221518043104131447711 / 2788815009188499086581352357412492142272
</syntaxhighlight>
=={{header|Rust}}==
<
use std::f32;
Line 1,550:
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,563:
class, which is effectively the same as passing by reference.
<
val i = new MyInt
def sum(i: MyInt, lo: Int, hi: Int, term: => Double) = {
Line 1,574:
temp
}
sum(i, 1, 100, 1.0 / i.i)</
Result:
Line 1,585:
Scheme procedures do not support call-by-name. Scheme macros, however, do:
<
(define-syntax sum
(syntax-rules ()
Line 1,595:
(loop (+ var 1)
(+ result . body)))))))
</syntaxhighlight>
<pre>
Line 1,605:
Seed7 supports call-by-name with function parameters:
<
$ include "seed7_05.s7i";
include "float.s7i";
Line 1,625:
writeln(sum(i, 1, 100, 1.0/flt(i)) digits 6);
end func;
</syntaxhighlight>
Output:
Line 1,633:
=={{header|Sidef}}==
<
func sum (i, lo, hi, term) {
var temp = 0;
Line 1,641:
return temp;
};
say sum(\i, 1, 100, { 1 / i });</
{{out}}
<pre>5.18737751763962026080511767565825315790899</pre>
Line 1,648:
{{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.<
begin
integer i;
Line 1,670:
comment note the correspondence between the mathematical notation and the call to sum;
outreal (sum (i, 1, 100, 1/i), 7, 14)
end</
{{out}}
<pre>
Line 1,677:
=={{header|Standard ML}}==
<
fun sum' (i, lo, hi, term) = let
Line 1,691:
val () =
print (Real.toString (sum' (i, 1, 100, fn () => 1.0 / real (!i))) ^ "\n")</
Output: 5.18737751764
=={{header|Swift}}==
<
func sum(inout i: Int, lo: Int, hi: Int, @autoclosure term: () -> Double) -> Double {
Line 1,705:
}
println(sum(&i, 1, 100, 1 / Double(i)))</
(Prior to Swift 1.2, replace <code>@autoclosure term: () -> Double</code> with <code>term: @autoclosure () -> Double</code>.)
{{out}}
Line 1,712:
=={{header|Tcl}}==
Here, we set the value of the passed variable in the caller's frame. We then evaluate the passed term there too.
<
upvar 1 $var x
set sum 0.0
Line 1,720:
return $sum
}
puts [sum i 1 100 {1.0/$i}] ;# 5.177377517639621</
However, the solution is expressed more simply like this
<
set sum 0.0
for {set n $lo} {$n < $hi} {incr n} {
Line 1,729:
return $sum
}
puts [sum2 1 100 {i {expr {1.0/$i}}}] ;# 5.177377517639621</
=={{header|VBA}}==
<syntaxhighlight 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,745:
Debug.Print sum("j", 1, 100, "sin(j)")
End Sub
</syntaxhighlight>
{{out}}
<pre>
Line 1,755:
=={{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.
<
construct new(v) { _v = v }
v { _v }
Line 1,774:
var s = sum.call(i, 1, 100, Fn.new { 1/i.v })
System.print(s)</
{{out}}
Line 1,784:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<
lo = 1 : hi = 100 : temp = 0
for i = lo to hi
Line 1,792:
end sub
Evaluation()</
{{out}}
<pre>
Line 1,801:
=={{header|zkl}}==
zkl doesn't support call by name/address but does have reference objects. Using an explicit call to 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();</
Using function application/deferred(lazy) objects, we can make the function call implicit (addition forces evaluation of the LHS):
<
temp:=0.0; ri.set(lo);
do{ temp=term + temp; } while(ri.inc()<hi); // inc return previous value
Line 1,814:
}
ri:=Ref(0);
sum2(ri, 1,100, 'wrap(){ 1.0/ri.value }).println();</
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:
<
sum3(1,100, fcn(i){ 1.0/i }).println();</
{{out}}
<pre>
Line 1,828:
=={{header|ZX Spectrum Basic}}==
<
20 LET f$="FN r(i)"
30 LET lo=1: LET hi=100
Line 1,840:
1040 NEXT i
1050 RETURN
</syntaxhighlight>
{{out}}
<pre>
|