multiple-value-constantly

2007-04-26

Improvement to Common Lisp:

Macro multiple-value-constantly

(multiple-value-constantly form*)

multiple-value-constantly evaluates each form, gathers all the values together, and yields a constant function that takes any number of arguments and returns the gathered values. It’s the spawn of multiple-value-call and constantly.

constantly could be defined as (defun constantly (it) (multiple-value-constantly it)).

Here’s my implementation:

(defmacro multiple-value-constantly (&rest forms)         
  `(multiple-value-call                                                         
    (lambda (&rest l) (lambda (&rest any)                                       
                        (declare (ignore any))                                  
                        (values-list l)))                                       
    ,@forms))

May induce funny feeling in Lisp programmers:

(setf (symbol-function 'constantly-nothing)
      (multiple-value-constantly))

(constantly-nothing)

Of course, you have to be careful using multiple values; they can be tricky.

About these ads

3 Responses to “multiple-value-constantly”

  1. Zach Beane Says:

    I don’t get why it’s a macro. Why not a function?

    (defun multiple-value-constantly (&rest values)
    (lambda (&rest rest)
    (declare (ignore rest))
    (values-list values)))

  2. Zach Beane Says:

    Ah, I see.

  3. drj11 Says:

    Thanks for asking Zach. It looks like you’ve enlightened yourself, but for the benefit of readers following along at home:

    It’s a macro not a function for the same reason that multiple-value-call is a special operator, so that it can accumulate the multiple values that each form produces:

    * (funcall (multiple-value-constantly (floor 5 2)))

    2
    1


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: