Nicholas Humphrey
Nicholas Humphrey

Reputation: 1250

Scheme: car and cdr

I'm reading this book: http://www.shido.info/lisp/scheme3_e.html

I'm stuck on this exercise:

(car '((1 2 3) (4 5 6)))

The thing is, from my understanding, I must understand how do we get ((1 2 3) (4 5 6)) to get (car '((1 2 3) (4 5 6))) because car evaluates the first address.

I tried a few times but cannot get the exact "string" (I don't even know how to call them):

(cons (cons 1 (cons 2 (cons 3 '()))) (cons 4 (cons 5 (cons 6 '())))) 

gives me

{{1 2 3} 4 5 6}

(cons (cons (cons 1 (cons 2 (cons 3 '()))) '()) (cons 4 (cons 5 (cons 6 '()))))

gives me

{{{1 2 3}} 4 5 6}

(cons (cons (cons 1 (cons 2 (cons 3 '()))) '()) (cons (cons 4 (cons 5 (cons 6 '()))) '()))

gives me

{{{1 2 3}} {4 5 6}}

At least I'm getting brackets for both parts...

The thing is, if each time I call car to get the first address, I need to formulate the result in my head to see the other side of the mountain, this seems to be an extremely difficult language to me...so I hope I'm wrong.

Upvotes: 1

Views: 308

Answers (1)

Dan D.
Dan D.

Reputation: 74685

'((1 2 3) (4 5 6)) is (cons (cons 1 (cons 2 (cons 3 '()))) (cons (cons 4 (cons 5 (cons 6 '()))) '()))

> (cons (cons 1 (cons 2 (cons 3 '()))) (cons (cons 4 (cons 5 (cons 6 '()))) '()))
'((1 2 3) (4 5 6))

If we replace the inner lists with symbols because their value does not matter we get:

(car '((1 2 3) (4 5 6)))
(car '(X Y))
(car (cons 'X (cons 'Y '())))

Which by the reduction (car (cons A B)) => A produces 'X so the result is (cons 1 (cons 2 (cons 3 '()))) or '(1 2 3)

Upvotes: 1

Related Questions