简体   繁体   中英

scheme - recursive function of lists

I have this program:

(define scale-tree
  (lambda (tree factor)
    (map (lambda (sub-tree)
           (if (list? sub-tree)
               (scale-tree sub-tree factor)
               (* sub-tree factor)))
         tree)))

(scale-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))
10)

How does this code work? First, we give it the whole list as parameter (list 1 (list 2 (list 3 4) 5) (list 6 7)) , and in the first call, the (lambda (sub-tree) gets the (list 1 (list 2 (list 3 4) 5) (list 6 7)) as parameter. For that, we call (scale-tree sub-tree factor) with (list 1 (list 2 (list 3 4) 5) (list 6 7)) again. When does the list reduce?

Thank you.

Remember what map does - it applies a function to every element of a list. So on the first call, this function:

(lambda (sub-tree)
           (if (list? sub-tree)
               (scale-tree sub-tree factor)
               (* sub-tree factor)))

is being applied to the elements of your list: 1 , (list 2 (list 3 4) 5) , and (list 6 7) . And so on in the recursive calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM