Exercise 1.4.14

List Position

When dealing with linked lists, if you want to get at a particular element somewhere in the middle, you could either chain some cars and cdrs.

* (car (cdr (cdr (cdr (list 0 1 2 3 4 5)))))
3

* (cadddr (list 0 1 2 3 4 5))
3

or you could use the nth function.

* (nth 3 (list 0 1 2 3 4 5))
3

* (nth 4 (list 0 1 2 3 4 5))
4

* (nth 5 (list 5 4 3 2 1 0))
0

This isn't any more efficient (in the run-time sense) than cdr traversal, but is shorter to write if you need to access some deeper list element in a flat list.

results matching ""

    No results matching ""