I'm noticing this function called rec
appear many times in Common Lisp code, but I'm not finding references to what it is actually doing. Could anyone explain to me what it is? For instance, it appears in some code from another question, How to convert a flat list into a nested tree-like structure?:
(defun mimicry (source pattern)
(labels ((rec (pattern)
(mapcar (lambda (x)
(if (atom x)
(pop source)
(rec x)))
pattern)))
(rec pattern)))
rec
is not a global function in you code unless you define it such yourself. It's an local auxiliary function defined with labels
.
The special operator labels
performs a similar task to defun
except the bindings are local. It's like you use defparameter
to make global variables and let
to make local ones.
(labels ((banana (arg1) ; make function banana
(+ arg1 arg1)))
(banana 10)) ; use it
; banana doesn't exist anymore
Is the same as:
(defun banan (arg1) ; make function banana
(+ arg1 arg1))
(banana 10) ; use it
; banana still exists
The difference is that banana ceases to exist on the outside of the labels
while with using defun
you are infesting your global environment with auxiliary functions. Since functions in labels
are local you can use common names like rec
, loop
and aux
as their names and they will not contaminate other parts of the code.
There is a similar special operator called flet
that works the same way but it doesn't include its own function in the local environment inhibiting you from calling your very own function in its body. These are useful too but you seldom call them rec
since rec
implies it's something recursive.
This is not a CL restriction but coding style. I do use the name rec
and loop
often in Scheme programming (another Lisp dialect) so when I come across them in CL I know what they are, but in CL I see from my answers on SO that I use aux
or test-aux
inside a global function called test
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With