The Little Schemer evens-only*&co

前端 未结 4 1521
失恋的感觉
失恋的感觉 2020-12-29 10:23

I\'m having difficulty understanding what\'s going on with The Little Schemer\'s evens-only*&co example on page 145.

Here\'s the code:



        
4条回答
  •  Happy的楠姐
    2020-12-29 10:35

    I have been reading How To Design Programs (felleisen et.al.). I am going through the section where they define local definitions. I have written a code that implements the above evens-only&co using a local definition. Here's what I wrote:

    (define (evens-only&co l)
      (local ((define (processing-func sum prod evlst lst)
                (cond ((null? lst) (cons sum (cons prod evlst)))
                      ((atom? (car lst))
                       (cond ((even? (car lst)) (processing-func sum (* prod (car lst)) (append evlst (list (car lst))) (cdr lst)))
                             (else
                              (processing-func (+ sum (car lst)) prod evlst (cdr lst)))))
                      (else
                       (local ((define inner-lst (processing-func sum prod  '() (car lst))))
                       (processing-func (car inner-lst) (cadr inner-lst) (append evlst (list (cddr inner-lst))) (cdr lst)))))))
        (processing-func 0 1 '() l)))
    

    For testing, when i enter (evens-only&co '((9 1 2 8) 3 10 ((9 9) 7 6) 2)) , it returns '(38 1920 (2 8) 10 (() 6) 2) as expected in the little schemer. But, my code fails in one condition: when there are no even numbers at all, the product of evens is still shown as 1. For example (evens-only&co '((9 1) 3 ((9 9) 7 ))) returns '(38 1 () (())). I guess i will need an additional function to rectify this. @melwasul: If you are not familiar with the local definition, sorry to post this here. I suggest you read HTDP too. It's an excellent book for beginners. But the guys who are experts in scheme can please post their comments on my code as well. Is my understanding of the local definition correct?

提交回复
热议问题