This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

first, rest, second, last

4 posts · 5973 views

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)?
(first '(() ()))
NIL

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

(second '(1 2 3))
2

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

Re: first, rest, second, last

first and rest is the same as car and cdr, which return parts of a cons cell. The internal structure of a list is:
(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.
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

Re: first, rest, second, last

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.
(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

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:
(last '(1 2 3) 2)
(2 3)