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

CL code is now closer to the first class functions entry, and both appear for comparison
m (move omits down, omit TI-BASIC)
(CL code is now closer to the first class functions entry, and both appear for comparison)
Line 23:
 
=={{header|Common Lisp}}==
{{incorrect|Common Lisp|Comparison/contrast missing.}}
<lang lisp>(defun multiplier (x y)
#'(lambda (z) (* x y z)))
 
<lang lisp>(defun first-class-numbersmultiplier (f g)
#'(let*lambda ((x) 2.0(* f g x)))
(xi 0.5)
(y 4.0)
(yi 0.25)
(z (+ x y))
(zi (/ 1.0 (+ x y)))
(left (list x y z))
(right (list xi yi zi)))
(loop for l in left
for r in right
do (format t "~&(funcall (multiplier ~w ~w) 0.5) = ~w"
l r (funcall (multiplier l r) 0.5)))))</lang>
 
(let* ((x 2.0)
<pre>> (first-class-numbers)
(xi 0.5)
(funcall (multiplier 2.0 0.5) 0.5) = 0.5
(y 4.0)
(funcall (multiplier 4.0 0.25) 0.5) = 0.5
(yi 0.25)
(funcall (multiplier 6.0 0.16666667) 0.5) = 0.5</pre>
#'(lambda (z) (*+ x y z)))
(zi (z/ 1.0 (+ x y)))
(zinumbers (/ 1.0 (+list x y) z))
(leftinverses (list xxi yyi zzi)))
(loop with value = 0.5
(loop for lnumber in leftnumbers
for rinverse in rightinverses
for multiplier = (multiplier number inverse)
do (format t "~&(funcall~A (multiplier* ~w A)(~w) 0.5A) = ~wA~%"
number
inverse
value
l r (funcall (multiplier l r) 0.5)value))))</lang>
 
Output:
 
(funcall (multiplier 2.0 * 0.5) (0.5) = 0.5
(funcall (multiplier 4.0 * 0.25) (0.5) = 0.5
(funcall (multiplier 6.0 * 0.16666667) (0.5) = 0.5</pre>
 
The code from [[First-class functions]], for comparison:
 
<lang lisp>(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))
 
(loop with value = 0.5
for function in (list #'sin #'cos #'cube )
for inverse in (list #'asin #'acos #'cube-root)
for composed = (compose inverse function)
do (format t "~&(~A ∘ ~A)(~A) = ~A~%"
inverse
function
value
(funcall composed value)))</lang>
 
Output:
 
(#<FUNCTION ASIN> ∘ #<FUNCTION SIN>)(0.5) = 0.5
(#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5
(#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5
 
=={{header|E}}==
Anonymous user