First-class functions/Use numbers analogously: Difference between revisions

Line 23:
 
=={{header|ALGOL 68}}==
{{trans|python}}{{wont work with|ALGOL 68|Revision 1 - scoping rules forbid exporting a procedure out of it's scope}}
 
{{wont work with|ALGOL 68|Revision 1 - scoping rules forbid exporting a procedure out of it's scope}}
 
{{wont work with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny] - scoping rules forbid exporting a procedure out of it's scope - detected at compile time and again at runtime}}
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
 
Note: Standard ALGOL 68's scoping rules forbids exporting a '''procedure''' (or '''format''') out of it's scope (closure). Hence this specimen will run on [[ELLA ALGOL 68]], but is non-standard. For a discussion of first-class functions in ALGOL 68 consult [http://www.cs.ru.nl/~kees/home/papers/psi96.pdf "The Making of Algol 68"] - [http://en.wikipedia.o.rg/wiki/Cornelis_H.A._Koster C.H.A. Koster] (1993). <!-- Retrieved April 28, 2007 -->
<lang algol68>REAL
x := REAL: 2;,
xi := REAL: 0.5;,
y := REAL: 4;,
yi := REAL: 0.25;,
z := REAL: x + y;,
zi := REAL: 1 / ( x + y );
 
<lang algol68>MODE FREALF = PROC (REAL)REAL;
FREAL x, xi, y, yi, z, zi;
 
PROC multiplier = (REAL n1, n2)F: ((REAL m)REAL: n1 * n2 * m);
# define the + and / operators for PROC REAL #
OP + = (FREAL a, b)FREAL: REAL: REAL(a)+REAL(b);
OP / = (FREAL a, b)FREAL: REAL: REAL(a)+REAL(b);
 
# Numbers as members of collections #
x := REAL: 2;
[]REAL num list = (x, y, z),
xi := REAL: 0.5;
inv num list = (xi, yi, zi);
y := REAL: 4;
yi := REAL: 0.25;
z := REAL: x + y;
zi := REAL: 1 / ( x + y );
 
# Apply numbers from list #
print((
FOR key TO UPB num list DO
"x: ",x, new line,
REAL n = num list[key],
"xi:",xi, new line,
inv n = inv num list[key];
"y: ",y, new line,
"yi:"print ((multiplier(inv n,yi n)(.5), new line,))
))OD</lang>
"z: ",z, new line,
"zi:",zi, new line
))</lang>
Output:
<pre>
+.500000000000000e +0
x: +.200000000000000e +1
xi: +.500000000000000e +0
+.500000000000000e +0
y: +.400000000000000e +1
yi: +.250000000000000e +0
z: +.600000000000000e +1
zi: +.166666666666667e +0
</pre>