Jensen's Device: Difference between revisions

→‎{{header|Forth}}: added macro-based variant
(→‎{{header|Forth}}: replaced FVARIABLE ii with VARIABLE i1 (i is integer in the task description))
(→‎{{header|Forth}}: added macro-based variant)
Line 741:
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> (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}}==
5

edits