Sunday, December 30, 2012

Closure in Lisp - example

This is a code that I borrowed from the book Practical Common Lips for closure in Lisp.
(defun artist-selector (artist)
  #'(lambda (cd) (equal (gets cd :artist) artist)))
In the code, artist-selector returns a closure that closes a variable "artist" over it. We can use this closure as a parameter to "select" function. Lisp supports high order function decades ago to enable it possible. "*db*" is a global variable.
(defun select (selector-fn)
  (remove-if-not selector-fn *db*))
The usage of "select" method is as follows. You can create another closure with different parameter to the "artist-selector" function.
(select (artist-selector "Dixie Chicks"))

References

No comments:

Post a Comment