How can I format alist in general lisp?

I'm starting to write regular Lisp to me, and I just put it all together and format them.

Suppose I have an alist, for example:

(defvar *map* '((0 . "zero") (1 . "one") (2 . "two")))

How do I format it?

0: zero
1: one
2: two

I thought something like (format t "~{~{~a: ~a~}~%~}" *map*), but this gives an error, because “zero” is not a list, and you cannot take it.

Course making (format t "~{~a~%~}" *map*)prints

(0 . "zero")
(1 . "one")
(2 . "two")

as expected, but that’s not quite what I want. Is there a better way to do this than just (dolist (entry *mapping*) (format t "~a: ~a~%" (car entry) (cdr entry)))?

+5
source share
5 answers

Channel # cl-gardeners on Freenode offers to bind the destructuring cycle as follows:

(loop for (a . b) in *mapping*
  do (format t "~a: ~a" a b))
+10

, , - cons FORMAT.

:

(defun print-assoc (stream arg colonp atsignp)
  (format stream "~A: ~A" (car arg) (cdr arg)))

:

(format t "~{~/print-assoc/~%~}" *map*)

, . , , , , print-assoc (), .

+6

, . cons, , . . :

(defvar *map* '((0 "zero") (1 "one") (2 "two")))
(format t "~:{~a: ~a~}" *map*)
+4

, ; map():

(format t "~{~a~%~}"
  (map 'list
    #'(lambda (entry)
      (format nil "~a: ~a" (car entry) (cdr entry))
    *map*))
+1

alist (a . 2) (a 2),

(mapcar #'(lambda (x) `(,(car x) ,(cdr x))) *map*)

.

For example, to print ((a . 2) (b . 3))as"a=2&b=3"

using

(format t "~{~{~a~^=~}~^&~}" (mapcar #'(lambda (x) `(,(car x) ,(cdr x))) *map*))
+1
source

All Articles