SICP Exercise 2.30 requires us to complete a process called Square-tree , which has the same effect as the square process before,Square The procedure is for a simple list, squares all the elements in the list, and then returns a new table of square columns. However, Square cannot handle nested lists, which can be an error if the list contains lists.
The topic requires us to implement a square-tree process where nested lists can be processed when the input list contains another list, resulting in the number of squares of all list elements.
This is the same as the previous several questions, is the tree-like List of the traversal and processing. The topic also requires that we do it in two ways, one that uses map and one that doesn't use maps.
First look at the method of not using map, is to continue to take the first element of the list, if the element is a simple number for the square, if the element is a list of recursive call Square-tree. Finishes processing the first element and then processes the contents of the subsequent CDR section.
The code is as follows:
(Define (Square-tree input-list) (if (null? input-list) ' () ( if (list? (Car input-list)) (Cons (Square-tree (Car input-list)) (Square-tree (Cdr input-list))) (Cons (Square car input-list) (Square-tree (Cdr input-list)))))
If you use a map , you do not have to traverse, directly using the map process for all elements, if the number is squared, if the list is recursive call square-tree-map.
(Define (Square-tree-map input-list) (Map (Lambda (i) ( if (list i) ( square-tree-map i) (square i))) input-list) (define (square x) ( * x x))
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
SICP exercises (2.30) Summing up the problem: Square-tree