Jensen's device <https://en.wikipedia.org/wiki/Jensen%27s_device> >demonstrates capabilities of Algol 60's call-by-name that later
programming languages have provided through other means. ><https://rosettacode.org/wiki/Jensen's_Device> shows solutions for
many other programming languages, including Forth.
The rosettacode task includes just one call to sum:
sum (i, 1, 100, 1/i)
This makes it easy to implement something that is not as general as
the Algol 60 version. This is shown particularly by the first Forth
version <https://rosettacode.org/wiki/Jensen's_Device#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.
It passes i on the stack. How would one use this SUM for the
following call given by wikipedia:
Sum(i, l, m, Sum(j, l, n, A[i,j]))
The second Forth version is as follows:
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.
The C entry points out that macros are close to call-by-name
semantics. Let's see how that works out in Gforth:
: ]sum ( compile-time: ) {: xt: i1 xt: term -- :}
\ run-time: ( lo hi -- r )
] ]] 0e 1+ swap +do
i i1 ! term f+
loop [[ ; immediate
variable i1
: term1 i1 @ s>f 1/f ;
: main2 ( -- )
[ ' i1 ] 1 100 [ ' term1 ]sum f. ;
main2 cr
Here main2 is decompiled as:
: main2 #1 #100
0.00000000000000E0 1+ swap
+do i i1 ! term1 f+
loop
f. ; ok
This variant reverts to using a global variable I1, because the macro
is expanded at compile-time and dealing with run-time locals in macros
is an unsolved problem in Gforth. It uses a named definition TERM1
rather than a quotation for better readability of the decompiler
output. The code of the macro is remarkably similar to the code of
the Gforth SUM above, thanks to ]] ... [[, and also the way
POSTPONE/]] treats defer-flavoured locals (it COMPILE,s them).
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 475 |
Nodes: | 16 (2 / 14) |
Uptime: | 19:53:44 |
Calls: | 9,487 |
Calls today: | 6 |
Files: | 13,617 |
Messages: | 6,121,093 |