## SICP – cap. 2 – Dati gerarchici e closure – 20

Continuo da qui, copio qui.

Operazioni sulle liste
The use of pairs to represent sequences of elements as lists is accompanied by conventional programming techniques for manipulating lists by successively “`cdr`ing down” the lists. For example, the procedure `list-ref` takes as arguments a `list` and a number `n` and returns the nth item of the `list`. It is customary to number the elements of the list beginning with 0. The method for computing `list-ref` is the following:

• For `n = 0` , list-ref should return the `car` of the list.
• Otherwise, `list-ref` should return the `(n − 1)-st` item of the `cdr` of the list.

Often we `cdr` down the whole list. To aid in this, Scheme includes a primitive predicate `null?`, which tests whether its argument is the empty list. The procedure `length`, which returns the number of items in a list, illustrates this typical pattern of use:

The `length` procedure implements a simple recursive plan. The reduction step is:

• The length of any list is 1 plus the length of the `cdr` of the list. This is applied successively until we reach the base case:
• The length of the empty list is 0.

We could also compute `length` in an iterative style:

Another conventional programming technique is to “`cons` up” an answer list while `cdr`ing down a list, as in the procedure `append`, which takes two lists as arguments and combines their elements to make a new list:

`append` is also implemented using a recursive plan. To append lists `list1` and `list2`, do the following:

• If `list1` is the empty list, then the result is just `list2`.
• Otherwise, append the `cdr` of `list1` and `list2`, and `cons` the `car` of `list1` onto the result:

Sì ho barato, di `quote` non si è ancora parlato 😊

Annunci
Posta un commento o usa questo indirizzo per il trackback.