Lisp Programming Trick #1


How many times have you created two function for setting a specific value and then getting the value?

(let ((value ""))
  (defun property (&key is)
      (is (setf value is))
      (t value)))
  ;;; here is getter and setter functions
  (defun get-property ()
  (defun set-property (data)
    (setf value data)))

(define-test get_set-property
  (assert-equal "" (get-property))
  (assert-equal "property" (set-property "property"))
  (assert-equal "property" (get-property))
  (assert-equal "" (set-property "")))

(define-test property
  (assert-equal "" (property))
  (assert-equal "property" (property :is "property"))
  (assert-equal "property" (property))
  (assert-equal "" (property :is ""))

Using a &key keyword parameter adds syntatic sugar to setting properties. It also means less typing.

It is done with a conditional. Another benefit is that behavior for the property is located in only one function instead of two functions.

New Use Case

(Zach Beane’s Request)

Need to be able to set the property to nil. Added the test to my unit tests. It failed. Modified the code and now it passes.

You just need to add a supplied-p parameter.

(let ((value ""))
  (defun property (&key (is nil is-p))
      (is-p (setf value is))
      (t value))))

(define-test property
  (assert-equal "" (property))
  (assert-equal "property" (property :is "property"))
  (assert-equal "property" (property))
  (assert-equal "" (property :is ""))
  (assert-equal nil (property :is nil)))

Happy Lisp Cargo-Culting!


7 Responses to Lisp Programming Trick #1

  1. Zach Beane says:

    Never. Who writes Lisp like that? Use CLOS.

  2. Zach Beane says:

    And what if you want to set something to NIL?

  3. Zach Beane says:

    It’s not a very good idea.

    • gutzofter says:

      How is it not a very good idea? What would be a better idea? I’m really interested in your thoughts on this.

  4. Zach Beane says:

    In Common Lisp, the setter for (FOO) looks like (SETF (FOO) …), not (FOO :IS …).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: