Church numerals: Difference between revisions

imported>Rowsety Moid
No edit summary
imported>Rowsety Moid
Line 683:
 
=={{header|Common Lisp}}==
 
In many solutions to this task, Church numerals are given a [[Currying|Curried]] form. In Common Lisp, that looks like this:
 
<pre>(lambda (f) (lambda (x) ...))</pre>
 
However, they can also be given an uncurried, 2-argument form:
 
<pre>(lambda (f x) ...)</pre>
 
Common Lisp has separate namespaces for variable and function names. When a variable, <code>f</code>, has a function as its value, the usual function-calling syntax, <code>(f ...)</code> can't be used to call the function; instead you have to write
<pre>(funcall f ...)</pre>
(<code>Funcall</code> is also needed when the function is the value of a more complex expression, rather than just a variable.)
 
<pre>
(n g v) ; uncurried, 1 namespace
((n g) v) ; curried, 1 namespace
(funcall n g v) ; uncurried, 2 namespaces
(funcall (funcall n g) v) ; curried, 2 namespaces
</pre>
 
===Uncurried Church numerals===
 
{{trans|Acornsoft Lisp}}
 
In this section, Church numerals are uncurried, 2-argument functions.
 
<syntaxhighlight lang="lisp">
Line 704 ⟶ 725:
(funcall n (lambda (product) (times m product)) one))
 
(defun church (i) ; int -> Church
(if (zerop i) zero (succ (church (1- i)))))
 
(defun unchurch (n) ; Church -> int
(funcall n #'1+ 0))
 
Line 740 ⟶ 761:
 
<syntaxhighlight lang="lisp">
(defvar zero (lambda (f) (lambda (x) x)))
 
(defvar one (lambda (f) (lambda (x) (funcall f x))))
 
Line 756 ⟶ 779:
(lambda (x) (funcall f (funcall g x))))
 
(defun church (i) ; int -> Church
(if (zerop i) zero (succ (church (1- i)))))
 
(defun unchurch (n) ; Church -> int
(funcall (funcall n #'1+) 0))
</syntaxhighlight>
Line 778 ⟶ 801:
(defun minus (m n)
(funcall n #'pred m))
</syntaxhighlight>
 
<syntaxhighlight lang="lisp">
(defmacro church-if (test then else)
`(funcall ,test (lambda () ,then) (lambda () ,else)))
Line 789 ⟶ 814:
(defun unbool (b)
(church-if b t nil))
</syntaxhighlight>
 
<syntaxhighlight lang="lisp">
(defun is-zero (n)
(funcall n (lambda (x) false) true))
Line 818 ⟶ 845:
 
===Further, curried===
 
Again, the remaining definitions, the calls to <code>show</code>, and the resulting output are the same as in uncurried version above.
 
<syntaxhighlight lang="lisp">
Anonymous user