SICP exercises (2.30) Summing up the problem: Square-tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.