7

Q: how can I convert a 2-item list to a dotted pair cons cell?

I can convert a 2-item list to a dotted pair with:

(let ((list '(1 2)))
  (cons (car list) (cadr list)))        ; => (1 . 2)

I'm blanking: is there a built-in function that does this, or should I roll my own?

  • 5
    Shameless plug: suggest is great in cases like this. Put your input as '(1 2), your output as '(1 . 2) and it will suggest (apply #'cons '(1 2)) for you! – Wilfred Hughes Sep 12 '16 at 3:08
11

cons makes a cons cell out of two arguments. apply uses a list as arguments to a function. When their powers combine: (apply #'cons x) converts a two element list into a cons cell (without having to poke around inside the list) and raises an error if the list isn't 2 long.

  • It's awesome how this is both more concise and includes proper error handling. – Daniel Jour Sep 12 '16 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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