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 |
This seems to satisfy the new problem statement: |
||
<lang j> |
<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 |
|||
⚫ | |||
B=: %A |
|||
4 |
|||
⚫ | |||
0.5 |
|||
⚫ | |||
6 |
|||
0.25 multiplier (2+4) (1%2+4) |
|||
0.25 |
|||
(2+4) multiplier (1%2+4) 2 |
|||
⚫ | |||
⚫ | |||
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. |
|||
⚫ | |||
Note that the following might be slightly more efficient: |
|||
Example use: |
|||
⚫ | |||
<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 |
|||
⚫ | |||
4 8 12 |
|||
⚫ | |||
⚫ | |||
=={{header|OCaml}}== |
=={{header|OCaml}}== |