Jump to content

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

rewrite with an attempted understanding of the new problem statement
(→‎{{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:
=={{header|J}}==
 
This seems to satisfy the currentnew problem statement:
 
<lang j> x multiplier=: conjunction def 'm * n * ]'</lang>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>
 
<lang j> multiplier=: conjunction def '(m * n) * ]'</lang>
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=: 4A multiplier 0.25 (2+4)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
0.5(A multiplier 4 (0.251) 2
4 8 12
<lang j> 2(3 multiplier 0.5B) (4)
6 3 2</lang>
 
=={{header|OCaml}}==
6,962

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.