Page 1 of 1

first, rest, second, last

Posted: Mon Aug 20, 2012 3:25 pm
by cos
Not really homework. But it is pretty basic, so I thought this forum was the best.
I'm brand new to Lisp and am working through the online tutorial:
http://art2.ph-freiburg.de/Lisp-Course

Why does first return NIL and rest return (NIL)?

Code: Select all

(first '(() ()))
NIL

(rest '(() ()))
(NIL)
Why does first return 1, second return 2, and last return (3)?

Code: Select all

(first '(1 2 3))
1

(second '(1 2 3))
2

(last '(1 2 3))
(3)
Many thanks,
COS

Re: first, rest, second, last

Posted: Tue Aug 21, 2012 12:46 am
by Goheeca
first and rest is the same as car and cdr, which return parts of a cons cell. The internal structure of a list is:

Code: Select all

(1 . (2 . (3 . nil))) ;(1 2 3)
The cons cells are those dotted pairs and car returns their first part and cdr returns the other part. last works similar to cdr in this respect.

Re: first, rest, second, last

Posted: Tue Aug 21, 2012 4:26 am
by saulgoode
cos wrote:Why does first return NIL and rest return (NIL)?
One can always be certain that there is only one first item in the list. Without knowing the length of the list, it is not possible to know how many items follow the first, so 'rest' returns them all as a list. Consider what (rest '(NIL NIL NIL)) evaluates to.
cos wrote:Why does first return 1, second return 2, and last return (3)?
This is a good question. One can always be certain that there is at most one 'last' item in a list, so it would seem reasonable that 'last' would return that item. However, if 'last' returned the car of the last cons cell then its behavior would be as expected for proper lists; but the result might seem unintuitive for an improper list.

Code: Select all

(car-last '(1 2 3)) ==> 3
; (1 2 3) is shorthand for (1 . (2 . (3 . nil)))
(car-last '(1 2 3 . 4)) ==> 3
; (1 2 3 . 4) is shorthand for (1 . (2 . (3 . 4)))
To make 'last' behave intuitively for both cases, it returns the last cons cell in both situations -- either (3 . nil) or (3 . 4) -- the former being the longhand version of the list (3)

Re: first, rest, second, last

Posted: Wed Aug 22, 2012 12:36 am
by Kompottkin
cos wrote:Why does first return 1, second return 2, and last return (3)?
The reason is that LAST does not return the last element of a list, but actually a list of the last N elements (actually the last N cons-cells), where N happens to default to 1:

Code: Select all

(last '(1 2 3) 2)
(2 3)