Jensen's Device: Difference between revisions

Content added Content deleted
(Added zkl)
Line 1,051: Line 1,051:
}
}
puts [sum2 1 100 {i {expr {1.0/$i}}}] ;# 5.177377517639621</lang>
puts [sum2 1 100 {i {expr {1.0/$i}}}] ;# 5.177377517639621</lang>

=={{header|zkl}}==
zkl doesn't support call by name/address but does have reference objects. Using an explicit call to term:
<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);
}
print("%f\n".fmt(sum(Ref(0), 1,100, fcn(ri){ 1.0 / ri.value })));</lang>
Using function application/deferred(lazy) objects, we can make the function call implicit (addition forces evaluation of the LHS):
<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
return(temp);
}
ri:=Ref(0);
print("%f\n".fmt(sum2(ri, 1,100, 'wrap(){ 1.0 / ri.value })));</lang>
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:
<lang zkl>fcn sum3(lo,hi, term){ [lo..hi].reduce('wrap(sum,i){sum+term(i) },0.0) }
print("%f\n".fmt(sum3(1,100, fcn(i){ 1.0 / i })));</lang>
{{out}}
<pre>
5.187378
5.187378
5.187378
</pre>


{{omit from|GUISS}}
{{omit from|GUISS}}