Reputation: 67
LISP stumps me yet again... Why can't I get the value of the last element in a list? I have a list set up similar to this:
(setq bar '(((1 2) 3 4 5)((6 7) 8 9 10)))
Now I get a return of 4 for:
(caddar bar)
There is a return of (5) for:
(cdddar bar)
But I can't get a 5 for:
(cadddar bar)
Why is this--and how do I get the value of the 5?
Error:
; Warning: This function is undefined:
; CADDDAR
Error in KERNEL:%COERCE-TO-FUNCTION: the function CADDDAR is undefined.
[Condition of type UNDEFINED-FUNCTION]
Upvotes: 2
Views: 2622
Reputation: 4708
The functions with more than 4 a
s and d
s aren't defined by the standard, maybe because there are 32 of them [and it gets exponentially messier from then on].
A sure-fire way to get the last element of a list: last
returns the last cons cell, so
(car (last list))
gives you the last list element. Of course, list
could be something else like (first list)
.
Upvotes: 2
Reputation: 139321
(first (last (first '(((1 2) 3 4 5) ((6 7) 8 9 10)))))
-> 5
Upvotes: 1
Reputation: 13983
The functions with 5 or more a's and d's are not defined. Only 4 and fewer. There are too many possible functions of that length for it be be practical.
You have to just spell it out:
(car (cdr (cdr (cdr (cdr (car x))))))
Upvotes: 9
Reputation: 7111
Well, per the error message, there is no cadddar
function. Keep in mind that car
and cdr
are the primitive list-reading functions. Others like caddar
are convenience functions that are built from a combination of one or more car
and cdr
. That is, you could perform list manipulation just fine with only car
and cdr
if caddar
etc. didn't exist, the extended functions just make your life a bit easier.
So, the way to approach this is to synthesize your own cadddar
using car
and cdr
. If it isn't immediately apparent how to do this, start simplier (with, say, cadr
or cdar
) and build up to cadddar
.
Upvotes: 2