Is there a function for the car of a car?

Viewed 50

In EOPL, can you return the car of the car without having to recursively go through the list?

In other words--is there a keyword that will return "apple" in the following example.

lst = '(apple banana strawberry) (milk cookie) (coke pepsi sprite)

The car is (apple banana strawberry). The car of the car would be apple.

1 Answers

Lisp-family languages have traditionally used the nice play on words that you use the middle part of a function whose name is 'c*r' to tell you which operations to perform, with a meaning 'take the car pointer' and d meaning 'take the cdr pointer'. So:

  • car means 'take the car of something';
  • `cadr' means 'take the car of the cdr of something';
  • 'cddaar' means 'take the cdr of the cdr of the car of the car of something'.

So for instance (cddaar '(((c y z)))) is (z).

And of course caar means 'take the car of the car of something', which is what you're after.

Note that these functions are not magic: in order to get the car of the car of something you have to check it's a cons, follow its car pointer, check the referenced object is a cons, and return its car, however you do it.

I think both Racket and Common Lisp have all combinations of up to four letters, which is 30 functions. There was at least one Lisp implementation which would invent these for you, so if you typed any function whose name matched this pattern it would define the function and call it.

This used to be more important than it is now: people spent a lot more time grovelling around in list structure than they do today, and before good compilers it was probably the case that code that said (caar x) was faster than code which said (car (car x))): that's probably not true now.

Related