Function composition: Difference between revisions

Emacs Lisp: Replace obsolete code with lexical binding example
(Added Mathcad example.)
(Emacs Lisp: Replace obsolete code with lexical binding example)
Line 914:
 
=={{header|Emacs Lisp}}==
 
A <code>lambda</code> form can be constructed with the desired <code>f</code> and <code>g</code> inserted. The result is simply a list. A list starting with <code>lambda</code> is a function.
Lexical binding is supported as of Emacs 24.1, allowing the use of a closure for function composition.
 
<lang Lisp>;; lexical-binding: t
(defun compose (f g)
(lambda (x)
(funcall f (funcall g x)))))
 
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 7</lang>
 
AAlternatively, a <code>lambda</code> form can be constructed with the desired <code>f</code> and <code>g</code> inserted. The result is simply a list. A list starting with <code>lambda</code> is a function.
 
<lang Lisp>(defun compose (f g)
Line 920 ⟶ 931:
 
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 7</lang>
=>
7</lang>
 
A similar thing can be done with a macro like the following. It differs in that the arguments should be unquoted symbols, and if they're expressions then they're evaluated on every call to the resulting <code>lambda</code>.
Line 930 ⟶ 939:
 
(let ((func (compose 1+ 1+)))
(funcall func 5)) ;=> 7</lang>
=>
7</lang>
 
Another possibility is the <code>cl.el</code> <code>lexical-let</code> to hold <code>f</code> and <code>g</code> for use in a new <code>lambda</code>.
 
<lang Lisp>(eval-when-compile (require 'cl)) ;; for `lexical-let' macro
(defun compose (f g)
(lexical-let ((f f)
(g g))
(lambda (x)
(funcall f (funcall g x)))))
 
(let ((func (compose '1+ '1+)))
(funcall func 5))
=>
7</lang>
 
=={{header|Erlang}}==
Anonymous user