I tried to use this code, but it returns (k k k k k)
(mapcar (lambda (x) 'cons x '(k))
'(a b c d e))
What am i doing wrong here? Why doesn't cons work?
Just syntax error. To create your alist, use to following:
(mapcar (lambda (x) (cons x 'k))
'(a b c d e))
(lambda (x) 'cons x '(k))
is a function which returns'(k)
(after a couple of pointless evaluations). That mapcar therefore should be returning((k) (k) (k) (k) (k))
which is different to what you've said.'(k)
in that context -- that's the exact same list being placed in each cell of that output. If you were tosetcar
any one of those(k)
instances to, say,j
, then not only would the entire list become((j) (j) (j) (j) (j))
, but the lambda function itself would now be returning that same'(j)
as well (unless it was re-read
). You frequently want(list 'k)
rather than'(k)
.