Lisp Pattern Matching

Posted by Daniel Lyons Sun, 24 Dec 2006 11:54:20 GMT

I don’t know to what degree this feature of the CLOS can be exploited, but one thing generally observed about Lisp is that crap like this:

(defun fib (x)
       (cond
         ((eq x 1) 1)
         ((eq x 2) 1)
         (t (+ (fib (1- x)) (fib (- x 2))))))

Is generally less readable and cool than crap like this in other languages (OCaml):

let rec fib = function
  | 1 -> 1
  | 2 -> 1
  | x -> fib (x - 1) + fib (x - 2) ;;

and Haskell:

fib 1 = 1
fib 2 = 1
fib x = fib (x - 1) + fib (x - 2)

But, you can use the CLOS to do primitive pattern matching (primitive, because I don’t think it can be used to do destructuring):

(defmethod fib ((x (eql 1))) 1)
(defmethod fib ((x (eql 2))) 1)
(defmethod fib ((x integer))
  (+ (fib (1- x)) (fib (- 2 x))))

Which is a little shorter, but adds a lot of nested parenthesis to the beginning of the method. Hmm.

Of course, only in Haskell can you get the list of all fibonacci numbers like this:

fibs = map fib [1..]

Or the eponymous self-recursive generator:

fibs = 1 : scanl (+) 1 fibs

To do the same thing with a series in Lisp requires some extra magic I don’t currently have.

Tags , , , ,  | no comments

Comments

(leave url/email »)

   Comment Markup Help Preview comment