1

I have a list of lists as follows in Common Lisp of the form

((1 2) (3 4) (5 6)) 

and which is the value of the variable list, and I want to have three new variables whose values are the elements of the list. For instance:

list-1 (1 2)
list-2 (3 4)
list-3 (5 6)

Is there any function which does this operation?

3 Answers 3

10

Use setq, first (or nth and elt) to set:

(setq list-1 (first list)
      list-2 (second list)
      list-3 (third list))

Or destructuring-bind to bind:

(destructuring-bind (list-1 list-2 list-3) list
  ...)

Again, destructuring-bind binds the variables instead of assigning them (i.e., it is like let, not like setq).

1
  • Also, instead of first, second, etc., you can use nth: (nth 0 list) returns '(1 2) .
    – zck
    Dec 31, 2012 at 20:12
2

The notion of binding elements of a list to names of the form list-# can be generalized.

You can create a function to generate a lambda with the ordinal list names as arguments, and a given body:

(defun make-list-lambda (n body)
  (let ((list-names (loop for index from 1 to n
     collect (intern (format nil "LIST-~D" index)))))
    `(lambda ,list-names
       (declare (ignorable ,@list-names))
       ,@body)))

And then create a macro to create the lambda, compile it, and apply it to the list:

(defmacro letlist (list &body body)
  (let ((assignments (gensym)))
    `(let ((,assignments ,list))
       (apply (compile nil (make-list-lambda (length ,assignments) ',body))
          ,assignments))))

In this way, the assignments are localized to the lambda body:

CL-USER> (letlist '(a b c d e f)
       (format t "list-1: ~A~%" list-1)
       (format t "list-3: ~A~%" list-3))
list-1: A
list-3: C
NIL

Note: The forms will be compiled every time the macro is invoked, since it will not be known how many list-# arguments will be present until the list is presented!

-1

First set your list to a variable, for instance mylist. Then spit out the required output using the function format. I'm using CLISP. Hope this helps. This is the actual REPL output.

(setf mylist '((1 2) (3 4) (5 6)) )

((1 2) (3 4) (5 6))

(format t "list-1 ~d~%list-2 ~d~%list-3 ~d" (car mylist) (second mylist) (last mylist)) list-1 (1 2) list-2 (3 4) list-3 ((5 6)) NIL [142]> Can someone show me how to get rid of "NIL' in the above output? I'm new to Lisp. Just learning for fun.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.