Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undocumented function called rec in Common Lisp source with labels?

Tags:

common-lisp

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)))
like image 451
dk123 Avatar asked Oct 05 '14 19:10

dk123


1 Answers

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.

like image 130
Sylwester Avatar answered Nov 09 '22 06:11

Sylwester