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

Content added Content deleted
(→‎{{header|D}}: Marked incorrect. Compare and contrast the resultant program with the corresponding entry in First-class functions.)
(rewrite with an attempted understanding of the new problem statement)
Line 229: Line 229:
=={{header|J}}==
=={{header|J}}==


This seems to satisfy the current problem statement:
This seems to satisfy the new problem statement:


<lang j> multiplier=: conjunction def 'm * n * ]'</lang>
<lang j> x =: 2.0
xi =: 0.5
y =: 4.0
yi =: 0.25
z =: x + y
zi =: 1.0 % ( x + y )


A=: x,y,z
<lang j> 2 multiplier 0.5 (4)
B=: %A
4
0.5 multiplier 4 (0.25)
0.5
4 multiplier 0.25 (2+4)
6
0.25 multiplier (2+4) (1%2+4)
0.25
(2+4) multiplier (1%2+4) 2
2</lang>


multiplier=: conjunction def '(m*n)*]'
J uses the concept of ''conjunctions'' to enable the composition of new verbs (functions). Conjunctions can link two verbs as in the [[First-class functions]] problem, analogous to the ''and'' in the phrase "cube and cuberoot". The [[First-class functions]] solution used the primitive conjunction <tt>@</tt> to link two verbs to create a new verb. The solution here uses a user-defined conjunction <tt>multiplier</tt> that links two nouns (numbers in this case) to create a new verb - something like "multiply m and n by y" where m and n are the nouns immediately to the left and right of the conjunction.


BA=: A multiplier B</lang>
Note that the following might be slightly more efficient:


Example use:
<lang j> multiplier=: conjunction def '(m * n) * ]'</lang>


<lang> BA 1
Here, the two constants are isolated from the rest of the calculation, so that multiplication is carried out only once, instead of every time the function is used.
1 1 1
(A multiplier 1) 2
4 8 12
(3 multiplier B) 4
6 3 2</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==