Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Labels in Common Lisp

In this question on code review I have been told to use labels instead of defun. I have looked on the internet, but I couldn't find any way to use it and still keep my code the way it is.

How could I use labels in my code?

like image 223
gumbo Avatar asked Sep 11 '11 21:09

gumbo


1 Answers

(defun example ()
  (let ((a 0)
        (f nil))
    (macrolet ((next (state)
                 `(setf f (function ,state))))
      (labels ((init ()
                 (setf a 0)
                 (next inc))
               (inc ()
                 (incf a)
                 (next inc)
                 (when (> a 5)
                   (next reset)))
               (reset ()
                 (setf a 0)
                 (next inc))
               (controller ()
                 (funcall f)
                 (print a)))
        (init)
        (loop repeat 20
              do (controller))))))

Example call:

CL-USER 7 > (example)

1 
2 
3 
4 
5 
6 
0 
1 
2 
3 
4 
5 
6 
0 
1 
2 
3 
4 
5 
6 
NIL
like image 138
Rainer Joswig Avatar answered Oct 12 '22 17:10

Rainer Joswig