Valentin Emil Cudelcu
Valentin Emil Cudelcu

Reputation: 43

Scheme explanation - cdr and car

I've got this example :

(apply + 2 (cdadr '(1 ((2 . 3) 4))))

This returns 6? Why is (cdadr '(1 ((2 . 3) 4))) 4?? I don't get it.Shouldn't it be 3?

Upvotes: 0

Views: 123

Answers (2)

soegaard
soegaard

Reputation: 31145

A list (a b c) is short for (a . (b . (c . ()))). Therefore '(1 ((2 . 3) 4))) is short for '(1 ((2 . 3) . (4 . ())) . ()).

To make sure, we test it in the REPL:

> ''(1 ((2 . 3) . (4 . ())) . ())
'(1 ((2 . 3)) 4)

cdadr is short for (cdr (car (cdr _))).

Here car extract the first part of a pair (car '(a . d)) = a and cdr extract the second part of a pair (cdr '(a . d)) = d

Let's see what happpens:

> (cdr '(1 ((2 . 3) . (4 . ())) . ()))
'(((2 . 3) 4))
> (car (cdr '(1 ((2 . 3) . (4 . ())) . ())))
'((2 . 3) 4)
> (cdr (car (cdr '(1 ((2 . 3) . (4 . ())) . ()))))
'(4)
> (apply + 2 '(4))
6

Note that ((2 . 3) 4) is the same as ((2 . 3) . (4 . ())) and that the cdr of this (4 .()) aka (4).

Upvotes: 1

molbdnilo
molbdnilo

Reputation: 66459

The result is the list '(4), not the number 4.

You have a list with two elements, where 1 is the first element, and the list ((2 . 3) 4) is the second element.

In other words, the cdr of the list is (cons ((2 . 3) 4)) '()), or (((2 . 3) 4)).

> (cdr '(1 ((2 . 3) 4)))
'(((2 . 3) 4))

This is a list with one element - the list ((2 . 3) 4) - which is of course the car.

> (car (cdr '(1 ((2 . 3) 4))))
'((2 . 3) 4)

and, finally,

> (cdr (car (cdr '(1 ((2 . 3) 4)))))
'(4)

Upvotes: 1

Related Questions