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?

1
  • 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! Commented Sep 12, 2016 at 3:08

1 Answer 1

12

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.

1
  • 1
    It's awesome how this is both more concise and includes proper error handling. Commented Sep 12, 2016 at 6:58

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.