用scheme重写Python的三大函数map reduce 和filter
2013-10-27 23:37
423 查看
重写过程中,发现这种做法能加深对递归的理解,而且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 >
相关文章推荐
- Python — lambda filter map reduce 函数介绍
- Python学习(五)函数 —— 内置函数 lambda filter map reduce
- python的几个内建函数:apply,filter,map,reduce
- python继承中重载问题:私有函数不能被子类重写
- Python内建函数之――filter,map,reduce
- [Python] 内置序列函数之 filter, map, reduce, zip
- python 常用函数 filter
- 简单介绍Python中的filter和lambda函数的使用
- python之filter()函数
- Python---高级函数map, filter, zip, enumerate等的用法
- Python 内建函数 - filter(function, iterable)
- Python 内建函数,filter,map, reduce
- Python小白学习之路(十五)—【map()函数】【filter()函数】【reduce()函数】
- python2 filter() map() reduce()函数基础
- python中的map(),reduce(),filter()函数
- Python 函数 filter() map() reduce()
- python常用函数之lambda、reduce、map、sorted、filter
- Python filter()函数
- python的几个内建函数:apply(),filter(),map(),reduce()
- python之高阶函数filter