开发者

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

开发者 https://www.devze.com 2023-04-04 19:25 出处:网络
开发者_JS百科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

开发者_JS百科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?


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消