Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

16. The Magic of Lisp Macros > More Complex Macros

More Complex Macros

Let’s suppose you need a custom my-length command. This is a classic list-eating function that will count the length of a list. We’ll write it in the proper “tail call optimized” style (discussed in Chapter 14), where the recursive function call is in the tail position. Here’s the code:

(defun my-length (lst)
   (labels ((f (lst acc)
              (if lst
                (f (cdr lst) (1+ acc))
                 acc)))
      (f lst 0)))

As you can see, this function has tons of repetitive stuff, once again giving us that dreaded feeling of déjà vu. There are two repetitive patterns in this function:

  • As in other list-eater functions, we have the annoying check to see if the list is empty and the associated use of cdr .


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint