Saturday, January 16, 2010

functions in plists

Common Lisp Plists are easy. A plist is just a list with properties. Any element with ":" prefixed is a property. The next element to a property is its value. We can then manipulate the plist using functions such as getf and setf. We give the property name to getf/setf and they fetch/set the appropriate property.

Here's a simple plist
'(:name "sid" :language "lisp")

Now, if we want to put in a function in the plist as a value, then the quote will not work.
'(:name "hello" :function (lambda () (format t "Hello World~%"))) ; Bad

The correct way is to backquote the plist and comma-escape the lambda.
`(:name "hello" :function ,(lambda () (format t "Hello World~%"))) 


We can then extract the function using getf and then finally call it using funcall. If we want to use an existing function, then we need to not only comma-escape but also add a #' so that the reader knows that a function symbol follows.

In C the equivalent would be to have a struct with a function pointer. What makes Lisp cool is that
  1. You can define an anonymous function in the plist itself
  2. You can have functions with different arity, inputs etc.. all in a list of plists. Lisp won't complain, but in C, the function pointer needs to be function of a particular signature only.
  3. Lisp also allows you to define structs which are more powerful than just plists, but a plist is good enough for this example.

No comments: