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))
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)