Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Jensen's_Device
note: Classic CS problems and programs

View file

@ -0,0 +1,32 @@
This task is an exercise in [[wp:Call-by-name#Call_by_name|call by name]].
'''Jensen's Device''' is a computer programming technique devised by Danish computer scientist [[wp:Jørn_Jensen|Jørn Jensen]] after studying the [[ALGOL 60]] Report.
The following program was proposed to illustrate the technique. It computes the 100th [[wp:Harmonic_number|harmonic number]]:
'''begin'''
'''integer''' i;
'''real procedure''' sum (i, lo, hi, term);
'''value''' lo, hi;
'''integer''' i, lo, hi;
'''real''' term;
'''comment''' term is passed by-name, and so is i;
'''begin'''
'''real''' temp;
temp := 0;
'''for''' i := lo '''step''' 1 '''until''' hi '''do'''
temp := temp + term;
sum := temp
'''end''';
'''comment''' note the correspondence between the mathematical notation and the call to sum;
print (sum (i, 1, 100, 1/i))
'''end'''
The above exploits [[wp:Call-by-name#Call_by_name|call by name]] to produce the correct answer (5.187...). It depends on the assumption that an expression passed as an actual parameter to a procedure would be re-evaluated in the caller's context every time the corresponding formal parameter's value was required. If the last parameter to ''sum'' had been passed by value, and assuming the initial value of ''i'' were 1, the result would have been 100 × 1/1 = 100.
Moreover, the ''first'' parameter to ''sum'', representing the "bound" variable of the summation, must also be passed by name (or at least by reference), otherwise changes to it (made within ''sum'') would not be visible in the caller's context when computing each of the values to be added.
(On the other hand, the global variable does not have to use the same identifier, in this case ''i'', as the formal parameter.)
[[wp:Donald_Knuth|Donald Knuth]] later proposed the [[Man or boy test|Man or Boy Test]] as a more rigorous exercise.
<br><br>

View file

@ -0,0 +1,13 @@
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()

View file

@ -0,0 +1,16 @@
BEGIN
INT i;
PROC sum = (REF INT i, INT lo, hi, PROC REAL term)REAL:
COMMENT term is passed by-name, and so is i COMMENT
BEGIN
REAL temp := 0;
i := lo;
WHILE i <= hi DO # ALGOL 68 has a "for" loop but it creates a distinct #
temp +:= term; # variable which would not be shared with the passed "i" #
i +:= 1 # Here the actual passed "i" is incremented. #
OD;
temp
END;
COMMENT note the correspondence between the mathematical notation and the call to sum COMMENT
print (sum (i, 1, 100, REAL: 1/i))
END

View file

@ -0,0 +1,17 @@
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.

View file

@ -0,0 +1,82 @@
/* ARM assembly Raspberry PI */
/* program jensen.s */
/* compil as with option -mcpu=<processor> -mfpu=vfpv4 -mfloat-abi=hard */
/* link with gcc */
/* Constantes */
.equ EXIT, 1 @ Linux syscall
/* Initialized data */
.data
szFormat: .asciz "Result = %.8f \n"
.align 4
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main:
mov r0,#1 @ first indice
mov r1,#100 @ last indice
adr r2,funcdiv @ address function
bl funcSum
vcvt.f64.f32 d1, s0 @ conversion double float for print by C
ldr r0,iAdrszFormat @ display format
vmov r2,r3,d1 @ parameter function printf for float double
bl printf @ display float double
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszFormat: .int szFormat
/******************************************************************/
/* function sum */
/******************************************************************/
/* r0 contains begin */
/* r1 contains end */
/* r2 contains address function */
/* r0 return result */
funcSum:
push {r0,r3,lr} @ save registers
mov r3,r0
mov r0,#0 @ init r0
vmov s3,r0 @ and s3
vcvt.f32.s32 s3, s3 @ convert in float single précision (32bits)
1: @ begin loop
mov r0,r3 @ loop indice -> parameter function
blx r2 @ call function address in r2
vadd.f32 s3,s0 @ addition float
add r3,#1 @ increment indice
cmp r3,r1 @ end ?
ble 1b @ no loop
vmov s0,s3 @ return float result in s0
100:
pop {r0,r3,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* compute 1/r0 */
/******************************************************************/
/* r0 contains the value */
/* r0 return result */
funcdiv:
push {r1,lr} @ save registers
vpush {s1} @ save float registers
cmp r0,#0 @ division by zero -> end
beq 100f
ldr r1,fUn @ load float constant 1.0
vmov s0,r1 @ in float register s3
vmov s1,r0 @
vcvt.f32.s32 s1, s1 @conversion in float single précision (32 bits)
vdiv.f32 s0,s0,s1 @ division 1/r0
@ and return result in s0
100:
vpop {s1} @ restaur float registers
pop {r1,lr} @ restaur registers
bx lr @ return
fUn: .float 1

View file

@ -0,0 +1,14 @@
# 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)
}

View file

@ -0,0 +1,26 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Jensen_Device is
function Sum
( I : not null access Float;
Lo, Hi : Float;
F : access function return Float
) return Float is
Temp : Float := 0.0;
begin
I.all := Lo;
while I.all <= Hi loop
Temp := Temp + F.all;
I.all := I.all + 1.0;
end loop;
return Temp;
end Sum;
I : aliased Float;
function Inv_I return Float is
begin
return 1.0 / I;
end Inv_I;
begin
Put_Line (Float'Image (Sum (I'Access, 1.0, 100.0, Inv_I'Access)));
end Jensen_Device;

View file

@ -0,0 +1,17 @@
set i to 0
on jsum(i, lo, hi, term)
set {temp, i's contents} to {0, lo}
repeat while i's contents hi
set {temp, i's contents} to {temp + (term's f(i)), (i's contents) + 1}
end repeat
return temp
end jsum
script term_func
on f(i)
return 1 / i
end f
end script
return jsum(a reference to i, 1, 100, term_func)

View file

@ -0,0 +1,7 @@
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}]

View file

@ -0,0 +1,10 @@
subroutine Evaluation()
lo = 1 : hi = 100 : temp = 0
for i = lo to hi
temp += (1/i) ##r(i)
next i
print temp
end subroutine
call Evaluation()
end

View file

@ -0,0 +1,11 @@
PRINT FNsum(j, 1, 100, FNreciprocal)
END
DEF FNsum(RETURN i, lo, hi, RETURN func)
LOCAL temp
FOR i = lo TO hi
temp += FN(^func)
NEXT
= temp
DEF FNreciprocal = 1/i

View file

@ -0,0 +1,14 @@
( ( sum
= I lo hi Term temp
. !arg:((=?I),?lo,?hi,(=?Term))
& 0:?temp
& !lo:?!I
& whl
' ( !!I:~>!hi
& !temp+!Term:?temp
& 1+!!I:?!I
)
& !temp
)
& sum$((=i),1,100,(=!i^-1))
);

View file

@ -0,0 +1,23 @@
#include <iostream>
#define SUM(i,lo,hi,term)\
[&](const int _lo,const int _hi){\
decltype(+(term)) sum{};\
for (i = _lo; i <= _hi; ++i) sum += (term);\
return sum;\
}((lo),(hi))
int i;
double sum(int &i, int lo, int hi, double (*term)()) {
double temp = 0;
for (i = lo; i <= hi; i++)
temp += term();
return temp;
}
double term_func() { return 1.0 / i; }
int main () {
std::cout << sum(i, 1, 100, term_func) << std::endl;
std::cout << SUM(i,1,100,1.0/i) << "\n";
return 0;
}

View file

@ -0,0 +1,20 @@
using System;
class JensensDevice
{
public static double Sum(ref int i, int lo, int hi, Func<double> term)
{
double temp = 0.0;
for (i = lo; i <= hi; i++)
{
temp += term();
}
return temp;
}
static void Main()
{
int i = 0;
Console.WriteLine(Sum(ref i, 1, 100, () => 1.0 / i));
}
}

View file

@ -0,0 +1,16 @@
#include <stdio.h>
int i;
double sum(int *i, int lo, int hi, double (*term)()) {
double temp = 0;
for (*i = lo; *i <= hi; (*i)++)
temp += term();
return temp;
}
double term_func() { return 1.0 / i; }
int main () {
printf("%f\n", sum(&i, 1, 100, term_func));
return 0;
}

View file

@ -0,0 +1,19 @@
#include <stdio.h>
int i;
#define sum(i, lo_byname, hi_byname, term) \
({ \
int lo = lo_byname; \
int hi = hi_byname; \
\
double temp = 0; \
for (i = lo; i <= hi; ++i) \
temp += term; \
temp; \
})
int main () {
printf("%f\n", sum(i, 1, 100, 1.0 / i));
return 0;
}

View file

@ -0,0 +1,20 @@
// Jensen's device in Clipper (or Harbour)
// A fairly direct translation of the Algol 60
// John M Skelton 11-Feb-2012
function main()
local i
? transform(sum(@i, 1, 100, {|| 1 / i}), "##.###############")
// @ is the quite rarely used pass by ref, {|| ...} is a
// code block (an anonymous function, here without arguments)
// The @i makes it clear that something unusual is occurring;
// a called function which modifies a parameter is commonly
// poor design!
return 0
function sum(i, lo, hi, bFunc)
local temp := 0
for i = lo to hi
temp += eval(bFunc)
next i
return temp

View file

@ -0,0 +1,7 @@
(declaim (inline %sum))
(defun %sum (lo hi func)
(loop for i from lo to hi sum (funcall func i)))
(defmacro sum (i lo hi term)
`(%sum ,lo ,hi (lambda (,i) ,term)))

View file

@ -0,0 +1,4 @@
CL-USER> (sum i 1 100 (/ 1 i))
14466636279520351160221518043104131447711/2788815009188499086581352357412492142272
CL-USER> (float (sum i 1 100 (/ 1 i)))
5.1873775

View file

@ -0,0 +1,12 @@
precision 4
define lo = 1, hi = 100, temp = 0
for i = lo to hi
let temp = temp + (1 / i)
wait
next i
print temp

View file

@ -0,0 +1,14 @@
double sum(ref int i, in int lo, in int hi, lazy double term)
pure @safe /*nothrow @nogc*/ {
double result = 0.0;
for (i = lo; i <= hi; i++)
result += term();
return result;
}
void main() {
import std.stdio;
int i;
sum(i, 1, 100, 1.0/i).writeln;
}

View file

@ -0,0 +1,12 @@
function sum(var i : Integer; lo, hi : Integer; lazy term : Float) : Float;
begin
i:=lo;
while i<=hi do begin
Result += term;
Inc(i);
end;
end;
var i : Integer;
PrintLn(sum(i, 1, 100, 1.0/i));

View file

@ -0,0 +1,25 @@
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;

View file

@ -0,0 +1,14 @@
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
i := lo
while (i <= hi) { # E has numeric-range iteration but it creates a distinct
temp += term # variable which would not be shared with the passed i
i += 1
}
return temp
}
{
var i := null
sum(&i, 1, 100, def _.get() { return 1/i })
}

View file

@ -0,0 +1,6 @@
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 })

View file

@ -0,0 +1,6 @@
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))

View file

@ -0,0 +1,11 @@
defmodule JensenDevice do
def task, do: sum( 1, 100, fn i -> 1 / i end )
defp sum( i, high, _term ) when i > high, do: 0
defp sum( i, high, term ) do
temp = term.( i )
temp + sum( i + 1, high, term )
end
end
IO.puts JensenDevice.task

View file

@ -0,0 +1,11 @@
-module( jensens_device ).
-export( [task/0] ).
task() ->
sum( 1, 100, fun (I) -> 1 / I end ).
sum( I, High, _Term ) when I > High -> 0;
sum( I, High, Term ) ->
Temp = Term( I ),
Temp + sum( I + 1, High, Term ).

View file

@ -0,0 +1,17 @@
begin
new i; new sum;
sum <- ` formal i; formal lo; formal hi; formal term;
begin
new temp; label loop;
temp <- 0;
i <- lo;
loop: begin
temp <- temp + term;
if [ i <- i + 1 ] <= hi then goto loop else 0
end;
temp
end
';
out sum( @i, 1, 100, `1/i' )
end $

View file

@ -0,0 +1 @@
printfn "%.14f" (List.fold(fun n g->n+1.0/g) 0.0 [1.0..100.0]);;

View file

@ -0,0 +1,3 @@
: sum ( lo hi term -- x ) [ [a,b] ] dip map-sum ; inline
1 100 [ recip ] sum .

View file

@ -0,0 +1,7 @@
SYMBOL: i
: sum ( i lo hi term -- x )
[ [a,b] ] dip pick [ inc ] curry compose map-sum nip ;
inline
i 1 100 [ recip ] sum .

View file

@ -0,0 +1,2 @@
: 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.

View file

@ -0,0 +1,6 @@
fvariable ii \ i is a Forth word that we need
: 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.

View file

@ -0,0 +1,8 @@
FUNCTION SUM(I,LO,HI,TERM)
SUM = 0
DO I = LO,HI
SUM = SUM + TERM
END DO
END FUNCTION SUM
WRITE (6,*) SUM(I,1,100,1.0/I)
END

View file

@ -0,0 +1,21 @@
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.
EXTERNAL TERM !Thus, not a variable, but a function.
SUMJ = 0
DO I = LO,HI !The specified span.
SUMJ = SUMJ + TERM(I) !Number and type of parameters now apparent.
END DO !TERM will be evaluated afresh, each time.
END FUNCTION SUMJ !So, almost there.
FUNCTION THIS(I) !A function of an integer.
INTEGER I
THIS = 1.0/I !Convert to floating-point.
END !Since 1/i will mostly give zero.
PROGRAM JENSEN !Aspiration.
EXTERNAL THIS !Thus, not a variable, but a function.
INTEGER I !But this is a variable, not a function.
WRITE (6,*) SUMJ(I,1,100,THIS) !No statement as to the parameters of THIS.
END

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,10 @@
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

View file

@ -0,0 +1,17 @@
package main
import "fmt"
var i int
func sum(i *int, lo, hi int, term func() float64) float64 {
temp := 0.0
for *i = lo; *i <= hi; (*i)++ {
temp += term()
}
return temp
}
func main() {
fmt.Printf("%f\n", sum(&i, 1, 100, func() float64 { return 1.0 / float64(i) }))
}

View file

@ -0,0 +1,5 @@
def sum = { i, lo, hi, term ->
(lo..hi).sum { i.value = it; term() }
}
def obj = [:]
println (sum(obj, 1, 100, { 1 / obj.value }))

View file

@ -0,0 +1,24 @@
import Control.Monad.ST
import Data.STRef
sum_ :: STRef s Double -> Double -> Double
-> ST s Double -> ST s Double
sum_ ref lo hi term =
do
vs <- forM [lo .. hi]
(\k -> do { writeSTRef ref k
; term } )
return $ sum vs
foo :: Double
foo =
runST $
do ref <- newSTRef undefined
-- initial value doesn't matter
sum_ ref 1 100 $
do
k <- readSTRef ref
return $ recip k
main :: IO ()
main = print foo

View file

@ -0,0 +1,15 @@
harmonic_sum( i, lo, hi, term ) {
temp = 0.0;
i *= 0.0;
i += lo;
while ( i <= hi ) {
temp += term();
i += 1.0;
}
return ( temp );
}
main() {
i = 0.0;
print( "{}\n".format( harmonic_sum( i, 1.0, 100.0, @[i](){ 1.0 / i; } ) ) );
}

View file

@ -0,0 +1,13 @@
record mutable(value) # record wrapper to provide mutable access to immutable types
procedure main()
A := mutable()
write( sum(A, 1, 100, create 1.0/A.value) )
end
procedure sum(A, lo, hi, term)
temp := 0
every A.value := lo to hi do
temp +:= @^term
return temp
end

View file

@ -0,0 +1,3 @@
write( sum(A, 1, 100, create |1.0/A.value) )
...
temp +:= @term

View file

@ -0,0 +1,6 @@
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]

View file

@ -0,0 +1,8 @@
jensen=: monad define
'name lo hi expression'=. y
temp=. 0
for_n. lo+i.1+hi-lo do.
(name)=. n
temp=. temp + ".expression
end.
)

View file

@ -0,0 +1,2 @@
jensen 'i';1;100;'1%i'
5.18738

View file

@ -0,0 +1,12 @@
import java.util.function.*;
import java.util.stream.*;
public class Jensen {
static double sum(int lo, int hi, IntToDoubleFunction f) {
return IntStream.rangeClosed(lo, hi).mapToDouble(f).sum();
}
public static void main(String args[]) {
System.out.println(sum(1, 100, (i -> 1.0/i)));
}
}

View file

@ -0,0 +1,21 @@
public class Jensen2 {
interface IntToDoubleFunction {
double apply(int n);
}
static double sum(int lo, int hi, IntToDoubleFunction f) {
double res = 0;
for (int i = lo; i <= hi; i++)
res += f.apply(i);
return res;
}
public static void main(String args[]) {
System.out.println(
sum(1, 100,
new IntToDoubleFunction() {
public double apply(int i) { return 1.0/i;}
}));
}
}

View file

@ -0,0 +1,11 @@
var obj;
function sum(o, lo, hi, term) {
var tmp = 0;
for (o.val = lo; o.val <= hi; o.val++)
tmp += term();
return tmp;
}
obj = {val: 0};
alert(sum(obj, 1, 100, function() {return 1 / obj.val}));

View file

@ -0,0 +1 @@
100 [0] [[1.0 swap /] dip +] primrec.

View file

@ -0,0 +1,5 @@
def sum(lo; hi; term):
reduce range(lo; hi+1) as $i (0; . + ($i|term));
# The task:
sum(1;100;1/.)

View file

@ -0,0 +1,14 @@
macro sum(i, loname, hiname, term)
return quote
lo = $loname
hi = $hiname
tmp = 0.0
for i in lo:hi
tmp += $term
end
return tmp
end
end
i = 0
@sum(i, 1, 100, 1.0 / i)

View file

@ -0,0 +1,3 @@
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 }))

View file

@ -0,0 +1,8 @@
{def jensen
{lambda {:n}
{+ {S.map {lambda {:i} {/ 1 :i}}
{S.serie 1 :n}} }}}
-> jensen
{jensen 100}
-> 5.187377517639621

View file

@ -0,0 +1,8 @@
function sum(var, a, b, str)
local ret = 0
for i = a, b do
ret = ret + setfenv(loadstring("return "..str), {[var] = i})()
end
return ret
end
print(sum("i", 1, 100, "1/i"))

View file

@ -0,0 +1,14 @@
Module Jensen`s_Device {
Def double i
Report Lazy$(1/i) ' display the definition of the lazy function
Function Sum (&i, lo, hi, &f()) {
def double temp
For i= lo to hi {
temp+=f()
}
=temp
}
Print Sum(&i, 1, 100, Lazy$(1/i))==5.1873775176392 ' true
Print i=101 ' true
}
Jensen`s_Device

View file

@ -0,0 +1,13 @@
Module Jensen`s_Device {
Def decimal i
Function Sum (&any, lo, hi, &f()) {
def decimal temp
For any= lo to hi {
temp+=f()
}
=temp
}
Print Sum(&i, 1, 100, Lazy$(1/i))=5.1873775176396202608051176755@ ' true
Print i=101 ' true
}
Jensen`s_Device

View file

@ -0,0 +1,13 @@
Module Jensen`s_Device {
Def single i
Function Sum (&any, lo, hi, &f()) {
def single temp
For any= lo to hi {
temp+=f()
}
=temp
}
Print Sum(&i, 1, 100, Lazy$(1/i))=5.187378~ ' true
Print i=101 ' true
}
Jensen`s_Device

View file

@ -0,0 +1,8 @@
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`sum',
`pushdef(`temp',0)`'for(`$1',$2,$3,
`define(`temp',eval(temp+$4))')`'temp`'popdef(`temp')')
sum(`i',1,100,`1000/i')

View file

@ -0,0 +1,4 @@
sum[term_, i_, lo_, hi_] := Block[{temp = 0},
Do[temp = temp + term, {i, lo, hi}];
temp];
SetAttributes[sum, HoldFirst];

View file

@ -0,0 +1,15 @@
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);
7381/2520
/* compare with builtin sum */
sum(1/n, n, 1, 10);
7381/2520
/* what if n is assigned a value ? */
n: 200$
/* still works */
mysum(1/n, n, 1, 10);
7381/2520

View file

@ -0,0 +1,36 @@
import COM.ibm.netrexx.process.
class JensensDevice
properties static
interpreter=NetRexxA
exp=Rexx ""
termMethod=Method
method main(x=String[]) static
say sum('i',1,100,'1/i')
method sum(i,lo,hi,term) static SIGNALS IOException,NoSuchMethodException,IllegalAccessException,InvocationTargetException
sum=0
loop iv=lo to hi
sum=sum+termeval(i,iv,term)
end
return sum
method termeval(i,iv,e) static returns Rexx SIGNALS IOException,NoSuchMethodException,IllegalAccessException,InvocationTargetException
if e\=exp then interpreter=null
exp=e
if interpreter=null then do
termpgm='method term('i'=Rexx) static returns rexx;return' e
fw=FileWriter("termpgm.nrx")
fw.write(termpgm,0,termpgm.length)
fw.close
interpreter=NetRexxA()
interpreter.parse([String 'termpgm.nrx'],[String 'nocrossref'])
termClass=interpreter.getClassObject(null,'termpgm')
classes=[interpreter.getClassObject('netrexx.lang', 'Rexx', 0)]
termMethod=termClass.getMethod('term', classes)
end
return Rexx termMethod.invoke(null,[iv])

View file

@ -0,0 +1,9 @@
var i: int
proc harmonicSum(i: var int; lo, hi: int; term: proc: float): float =
i = lo
while i <= hi:
result += term()
inc i
echo harmonicSum(i, 1, 100, proc: float = 1 / i)

View file

@ -0,0 +1,13 @@
let i = ref 42 (* initial value doesn't matter *)
let sum' i lo hi term =
let result = ref 0. in
i := lo;
while !i <= hi do
result := !result +. term ();
incr i
done;
!result
let () =
Printf.printf "%f\n" (sum' i 1 100 (fun () -> 1. /. float !i))

View file

@ -0,0 +1,23 @@
bundle Default {
class Jensens {
i : static : Int;
function : Sum(lo : Int, hi : Int, term : () ~ Float) ~ Float {
temp := 0.0;
for(i := lo; i <= hi; i += 1;) {
temp += term();
};
return temp;
}
function : term() ~ Float {
return 1.0 / i;
}
function : Main(args : String[]) ~ Nil {
Sum(1, 100, term() ~ Float)->PrintLine();
}
}
}

View file

@ -0,0 +1 @@
: mysum(lo, hi, term) | i | 0 lo hi for: i [ i term perform + ] ;

View file

@ -0,0 +1,14 @@
declare
fun {Sum I Lo Hi Term}
Temp = {NewCell 0.0}
in
I := Lo
for while:@I =< Hi do
Temp := @Temp + {Term}
I := @I + 1
end
@Temp
end
I = {NewCell unit}
in
{Show {Sum I 1 100 fun {$} 1.0 / {Int.toFloat @I} end}}

View file

@ -0,0 +1,6 @@
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}}

View file

@ -0,0 +1,24 @@
$i;
function sum (&$i, $lo, $hi, $term) {
$temp = 0;
for ($i = $lo; $i <= $hi; $i++) {
$temp += $term();
}
return $temp;
}
echo sum($i, 1, 100, create_function('', 'global $i; return 1 / $i;')), "\n";
//Output: 5.18737751764 (5.1873775176396)
function sum ($lo,$hi)
{
$temp = 0;
for ($i = $lo; $i <= $hi; $i++)
{
$temp += (1 / $i);
}
return $temp;
}
echo sum(1,100);
//Output: 5.1873775176396

View file

@ -0,0 +1,32 @@
program Jensens_Device;
{$IFDEF FPC}
{$MODE objFPC}
{$ENDIF}
type
tTerm = function(i: integer): real;
function term(i: integer): real;
begin
term := 1 / i;
end;
function sum(var i: LongInt; lo, hi: integer; term: tTerm): real;
begin
result := 0;
i := lo;
while i <= hi do
begin
result := result + term(i);
inc(i);
end;
end;
var
i: LongInt;
begin
writeln(sum(i, 1, 100, @term));
{$IFNDEF UNIX} readln; {$ENDIF}
end.

View file

@ -0,0 +1,11 @@
my $i;
sub sum {
my ($i, $lo, $hi, $term) = @_;
my $temp = 0;
for ($$i = $lo; $$i <= $hi; $$i++) {
$temp += $term->();
}
return $temp;
}
print sum(\$i, 1, 100, sub { 1 / $i }), "\n";

View file

@ -0,0 +1,11 @@
my $i;
sub sum {
my (undef, $lo, $hi, $term) = @_;
my $temp = 0;
for ($_[0] = $lo; $_[0] <= $hi; $_[0]++) {
$temp += $term->();
}
return $temp;
}
print sum($i, 1, 100, sub { 1 / $i }), "\n";

View file

@ -0,0 +1,14 @@
(phixonline)-->
<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>
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<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>
<!--

View file

@ -0,0 +1,14 @@
(scl 6)
(de jensen (I Lo Hi Term)
(let Temp 0
(set I Lo)
(while (>= Hi (val I))
(inc 'Temp (Term))
(inc I) )
Temp ) )
(let I (box) # Create indirect reference
(format
(jensen I 1 100 '(() (*/ 1.0 (val I))))
*Scl ) )

View file

@ -0,0 +1,17 @@
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())

View file

@ -0,0 +1,18 @@
class Ref(object):
def __init__(self, value=None):
self.value = value
def harmonic_sum(i, lo, hi, term):
# term is passed by-name, and so is i
temp = 0
i.value = lo
while i.value <= hi: # Python "for" loop creates a distinct which
temp += term() # would not be shared with the passed "i"
i.value += 1 # Here the actual passed "i" is incremented.
return temp
i = Ref()
# 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)

View file

@ -0,0 +1,5 @@
def harmonic_sum(i, lo, hi, term):
return sum(term() for i[0] in range(lo, hi + 1))
i = [0]
print(harmonic_sum(i, 1, 100, lambda: 1.0 / i[0]))

View file

@ -0,0 +1,5 @@
def harmonic_sum(i, lo, hi, term):
return sum(eval(term) for i[0] in range(lo, hi + 1))
i = [0]
print(harmonic_sum(i, 1, 100, "1.0 / i[0]"))

View file

@ -0,0 +1,15 @@
sum <- function(var, lo, hi, term)
eval(substitute({
.temp <- 0;
for (var in lo:hi) {
.temp <- .temp + term
}
.temp
}, as.list(match.call()[-1])),
enclos=parent.frame())
sum(i, 1, 100, 1/i) #prints 5.187378
##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

View file

@ -0,0 +1,17 @@
/*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.*/
numeric digits d /*use D decimal digits (9 is default)*/
say 'using ' d " decimal digits:" /*display what's being used for digits.*/
say
say sum( i, 1, 100, "1/i" ) /*invoke SUM (100th harmonic number).*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sum: procedure; parse arg j,start,finish,exp; $= 0
interpret 'do' j "=" start 'to' finish "; $=$+" exp '; end'
/*comment ──── ═ ─── ═════ ──── ══════ ────────── ═══ ───────── */
/*comment lit var lit var lit var literal var literal */
return $

View file

@ -0,0 +1,18 @@
#lang algol60
begin
integer i;
real procedure sum (i, lo, hi, term);
value lo, hi;
integer i, lo, hi;
real term;
comment term is passed by-name, and so is i;
begin
real temp;
temp := 0;
for i := lo step 1 until hi do
temp := temp + term;
sum := temp
end;
comment note the correspondence between the mathematical notation and the call to sum;
printnln (sum (i, 1, 100, 1/i))
end

View file

@ -0,0 +1,4 @@
#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)))

View file

@ -0,0 +1,10 @@
sub sum($i is rw, $lo, $hi, &term) {
my $temp = 0;
loop ($i = $lo; $i <= $hi; $i++) {
$temp += term;
}
return $temp;
}
my $i;
say sum $i, 1, 100, { 1 / $i };

View file

@ -0,0 +1,7 @@
public num Jenssen(int lo, int hi, num (int i) term){
temp = 0;
while (lo <= hi){
temp += term(lo);
lo += 1;}
return temp;
}

View file

@ -0,0 +1,2 @@
rascal>Jenssen(1, 100, num(int i){return 1.0/i;})
num: 5.18737751763962026080511767565825315790897212670845165317653395662

View file

@ -0,0 +1,13 @@
# Project : Jensen's Device
decimals(14)
i = 100
see sum(i,1,100,"1/n") + nl
func sum(i,lo,hi,term)
temp = 0
for n = lo to hi step 1
eval("num = " + term)
temp = temp + num
next
return temp

View file

@ -0,0 +1,8 @@
def sum(var, lo, hi, term, context)
sum = 0.0
lo.upto(hi) do |n|
sum += eval "#{var} = #{n}; #{term}", context
end
sum
end
p sum "i", 1, 100, "1.0 / i", binding # => 5.18737751763962

View file

@ -0,0 +1,4 @@
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

View file

@ -0,0 +1,6 @@
def sum lo, hi, &term
(lo..hi).sum(&term)
end
p sum(1,100){|i| 1.0/i} # => 5.187377517639621
# or using Rational:
p sum(1,100){|i| Rational(1,i)} # => 14466636279520351160221518043104131447711 / 2788815009188499086581352357412492142272

View file

@ -0,0 +1,12 @@
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));
}

View file

@ -0,0 +1,12 @@
class MyInt { var i: Int = _ }
val i = new MyInt
def sum(i: MyInt, lo: Int, hi: Int, term: => Double) = {
var temp = 0.0
i.i = lo
while(i.i <= hi) {
temp = temp + term
i.i += 1
}
temp
}
sum(i, 1, 100, 1.0 / i.i)

View file

@ -0,0 +1,9 @@
(define-syntax sum
(syntax-rules ()
((sum var low high . body)
(let loop ((var low)
(result 0))
(if (> var high)
result
(loop (+ var 1)
(+ result . body)))))))

View file

@ -0,0 +1,19 @@
$ include "seed7_05.s7i";
include "float.s7i";
var integer: i is 0;
const func float: sum (inout integer: i, in integer: lo, in integer: hi,
ref func float: term) is func
result
var float: sum is 0.0
begin
for i range lo to hi do
sum +:= term;
end for;
end func;
const proc: main is func
begin
writeln(sum(i, 1, 100, 1.0/flt(i)) digits 6);
end func;

View file

@ -0,0 +1,9 @@
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 });

View file

@ -0,0 +1,23 @@
comment Jensen's Device;
begin
integer i;
real procedure sum (i, lo, hi, term);
name i, term;
value lo, hi;
integer i, lo, hi;
real term;
comment term is passed by-name, and so is i;
begin
integer j;
real temp;
temp := 0;
for j := lo step 1 until hi do
begin
i := j;
temp := temp + term
end;
sum := temp
end;
comment note the correspondence between the mathematical notation and the call to sum;
outreal (sum (i, 1, 100, 1/i), 7, 14)
end

View file

@ -0,0 +1,15 @@
val i = ref 42 (* initial value doesn't matter *)
fun sum' (i, lo, hi, term) = let
val result = ref 0.0
in
i := lo;
while !i <= hi do (
result := !result + term ();
i := !i + 1
);
!result
end
val () =
print (Real.toString (sum' (i, 1, 100, fn () => 1.0 / real (!i))) ^ "\n")

View file

@ -0,0 +1,11 @@
var i = 42 // initial value doesn't matter
func sum(inout i: Int, lo: Int, hi: Int, @autoclosure term: () -> Double) -> Double {
var result = 0.0
for i = lo; i <= hi; i++ {
result += term()
}
return result
}
println(sum(&i, 1, 100, 1 / Double(i)))

View file

@ -0,0 +1,9 @@
proc sum {var lo hi term} {
upvar 1 $var x
set sum 0.0
for {set x $lo} {$x < $hi} {incr x} {
set sum [expr {$sum + [uplevel 1 [list expr $term]]}]
}
return $sum
}
puts [sum i 1 100 {1.0/$i}] ;# 5.177377517639621

Some files were not shown because too many files have changed in this diff Show more