Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a structure's constructor evaluate sequentially in Common Lisp?

I would like to do something akin to this:

(defstruct person
  real-name
  (fake-name real-name)) ;if fake-name not supplied, default to real-name

However, Common Lisp says The variable REAL-NAME is unbound. So how can I get the constructor to evaluate its arguments sequentially (like I can with function keyword arguments), or how else should I be better doing this?

like image 575
wrongusername Avatar asked Sep 15 '11 04:09

wrongusername


1 Answers

One way is:

(defstruct (person
             (:constructor make-person (&key real-name
                                             (fake-name real-name))))
  real-name
  fake-name)

You can essentially tailor the constructor function to your needs, including

  • providing a different name than make-xxx
  • having Lisp generate a "by-order-of-arguments" (BOA) constructor instead of a keyword-based one

Consider

(defstruct (person 
             (:constructor make-person (real-name
                                        &optional (fake-name real-name))))
    real-name
    fake-name)

You can even initialize constructed fields using the &aux lambda-list keyword:

(defstruct (person
             (:constructor make-person (real-name
                                        &aux (fake-name (format nil
                                                                "fake-of-~A"
                                                                real-name)))))
    real-name
    fake-name)
like image 185
Dirk Avatar answered Sep 28 '22 06:09

Dirk