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

Content added Content deleted
(Undo revision 136943 by Xutpuk (talk) Task *requires* a comparison!)
(Added BBC BASIC)
Line 106: Line 106:
</lang>
</lang>
- which has the same output.
- which has the same output.

=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> REM Create some numeric variables:
x = 2 : xi = 1/2
y = 4 : yi = 0.25
z = x + y : zi = 1 / (x + y)
REM Create the collections (here structures are used):
DIM c{x, y, z}
DIM ci{x, y, z}
c.x = x : c.y = y : c.z = z
ci.x = xi : ci.y = yi : ci.z = zi
REM Create some multiplier functions:
multx = FNmultiplier(c.x, ci.x)
multy = FNmultiplier(c.y, ci.y)
multz = FNmultiplier(c.z, ci.z)
REM Test applying the compositions:
x = 1.234567 : PRINT x " ", FN(multx)(x)
x = 2.345678 : PRINT x " ", FN(multy)(x)
x = 3.456789 : PRINT x " ", FN(multz)(x)
END
DEF FNmultiplier(n1,n2)
LOCAL f$, p%
f$ = "(m)=" + STR$n1 + "*" + STR$n2 + "*m"
DIM p% LEN(f$) + 4
$(p%+4) = f$ : !p% = p%+4
= p%</lang>
'''Output:'''
<pre>
1.234567 1.234567
2.345678 2.345678
3.456789 3.45678901
</pre>
Compare with the implementation of First-class functions:
<lang bbcbasic> REM Create some functions and their inverses:
DEF FNsin(a) = SIN(a)
DEF FNasn(a) = ASN(a)
DEF FNcos(a) = COS(a)
DEF FNacs(a) = ACS(a)
DEF FNcube(a) = a^3
DEF FNroot(a) = a^(1/3)
dummy = FNsin(1)
REM Create the collections (here structures are used):
DIM cA{Sin%, Cos%, Cube%}
DIM cB{Asn%, Acs%, Root%}
cA.Sin% = ^FNsin() : cA.Cos% = ^FNcos() : cA.Cube% = ^FNcube()
cB.Asn% = ^FNasn() : cB.Acs% = ^FNacs() : cB.Root% = ^FNroot()
REM Create some function compositions:
AsnSin% = FNcompose(cB.Asn%, cA.Sin%)
AcsCos% = FNcompose(cB.Acs%, cA.Cos%)
RootCube% = FNcompose(cB.Root%, cA.Cube%)
REM Test applying the compositions:
x = 1.234567 : PRINT x, FN(AsnSin%)(x)
x = 2.345678 : PRINT x, FN(AcsCos%)(x)
x = 3.456789 : PRINT x, FN(RootCube%)(x)
END
DEF FNcompose(f%,g%)
LOCAL f$, p%
f$ = "(x)=" + CHR$&A4 + "(&" + STR$~f% + ")(" + \
\ CHR$&A4 + "(&" + STR$~g% + ")(x))"
DIM p% LEN(f$) + 4
$(p%+4) = f$ : !p% = p%+4
= p%</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==