7

I have two vectors, [apple orange] and [5 10]. How do I construct an association list ((apple 5) (orange 10)) from them?

11

You can use cl-pairlis:

(require 'cl-lib)

(cl-pairlis '(apple orange) '(5 10))
;; =>
;; ((apple . 5) (orange . 10))

Also works for vectors:

(cl-pairlis [apple orange] [5 10])
;; =>
;; ((apple . 5) (orange . 10))

(The cl library defines the shorter alias pairlis for cl-pairlis, but this is deprecated in newer Emacs versions.)

  • Hi abo-abo, It works like magic! I'd like to save the association list to a file, do you know any good function for this? (insert doesn't work)... – yi.tang.uni May 15 '15 at 10:25
  • (insert (prin1-to-string (pairlis [apple orange] [5 10]))) – abo-abo May 15 '15 at 10:34
  • Interesting, I didn't realise it works on vectors (which would appear to be an undocumented feature). – jch May 15 '15 at 10:49
  • @abo-abo that's great, thank you very much! saved me a lot time googling! – yi.tang.uni May 15 '15 at 13:20
11

(cl-mapcar #'cons [apple orange] [5 10]) => ((apple . 5) (orange . 10))

(cl-mapcar #'list [apple orange] [5 10]) => ((apple 5) (orange 10))

Emacs's cl-mapcar takes as arguments a function of arity one or more and the same number of sequences as its arity. Common Lisp's mapcar is similar, but the only sequences it accepts are lists.

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.