Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Lisp newbie-ass question (CL)

Name: Anonymous 2011-06-28 4:29

I want to return the value from a list that looks like(key value). I've got an alist like ((a 1) (b 2) (c 3)) (as alists go), and I get a value given a key with assoc, but the returned value for (assoc 'a myalist) is (A 1).

I can get just the key from that with cdr, but that will return (1), still a list, and I might want to use that value eg. for addition.  So I do: (car (cdr (assoc 'a myalist))) to get 1

Is this as good as any other way?  Or is there some other preferred way of doing it, maybe with 1 function instead of (car (cdr (key val)) or something?

I'm really new to Lisp, so any useful information at all is appreciated.

Name: Anonymous 2011-06-28 21:19

Use CADR or SECOND, or just format your alist as (cons a b) == '(a . b)
>>12
What is the advantage of doing ((k . v)) over ((k v)) ?
A proper list is just a CONS whose CAR represents the start of the list and whose CDR represents the continuation of the list. If the CDR is NIL, it is the end of the list (NIL is the same as '()).
Dot notation just lets you represent a list's CDR element without making a proper list, so saying (k . v) is similar to saying (cons k v), while [/m](k v)[/m] is similar to saying (cons k (list 'v)) or (cons k (cons v nil)). It should also be noted that dot notation is a bit more extensive and you can just use it whenever you want to specify the last CDR, like this: '(a b . c). You may also want to learn about backquote and other fancy syntaxes, but pretty much all notation can be expanded into plain S-Expressions and atoms (you can play with the printer/reader to see underneath various objects if you so wish, for example:

CL-USER> '`(a ,b)
`(A ,B)
CL-USER> (setf *print-pretty* nil)
NIL
CL-USER> **
(SB-IMPL::BACKQ-LIST (QUOTE A) B)

SB-IMPL::BACKQ-LIST is functionally equivalent to LIST, but a different symbol is used so the implementation's pretty printer hook can properly print backquoted expressions (you could easily implement your own, this is supported in standard CL, and you can even see one such implementation in CLTL2 (book))

In general this should all be explained in the right books. What are you using? I would recommend having/reading Practical Common Lisp, Hyperspec, Common Lisp The Language 2, Art of the Metaobject Protocol. There are also various other introductory books such as Graham's ANSI CL, Common Lisp: A Gentle Introduction to Symbolic Computation, Land of Lisp, and quite a few others.

You should also read SICP if you haven't already and maybe also "LISP in Small Pieces".

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List