用scheme重写Python的三大函数map reduce 和filter
重写过程中,发现这种做法能加深对递归的理解,而且reduce还体现了函数式编程是如何通过参数传递来实现命令式编程中的状态改变的.
(define (imap f x . y) (if (null? y) (let recur ((x x)) (if (null? x) '() (cons (f (car x)) (recur (cdr x))))) (let recur ((x x) (y y)) (if (null? x) '() (cons (apply f (car x) (imap car y)) (recur (cdr x) (imap cdr y))))))) (map + '(1 2 3) '(1 2 3) '(1 2 3)) (imap + '(1 2 3) '(1 2 3) '(1 2 3)) (define (filter f x) (let recur ((x x)) (if (null? x) '() (if (f (car x)) (cons (car x) (recur (cdr x))) (recur (cdr x)))))) (filter even? '(1 2 3 4 5)) (define (reduce f x . ini) (if (null? ini) (let recur ((res (f (car x) (cadr x)))(x (cddr x))) (if (null? x) res (recur (f res (car x)) (cdr x)))) (reduce f (cons (car ini) x)))) (reduce + '(1 2 3 4)) (reduce + '(1 2 3 4) 10) (reduce * '(1 2 3 4)) (reduce * '(1 2 3 4) 10)
结果:
(3 6 9) (3 6 9) (2 4) 10 20 24 240 >