Clojure语言十一:map函数

来源:互联网 发布:羊毛 起球 知乎 编辑:程序博客网 时间:2024/05/16 09:57

map函数比较特别,首先看一个简单的功能:

user=> (def f (fn [x] (+ 2 x)))#'user/fuser=> (map f [2 4 7])(4 6 9)

先定义了一个f函数,接受一个参数,然后返回+2后的结果。

map接受两个参数,第一个是f函数,第二个是一个数组。用数组中的三个元素依次调用f函数,每次调用的结果加入到一个list中并返回。


map的文档:

-------------------------clojure.core/map([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])  Returns a lazy sequence consisting of the result of applying f to the  set of first items of each coll, followed by applying f to the set  of second items in each coll, until any one of the colls is  exhausted.  Any remaining items in other colls are ignored. Function  f should accept number-of-colls arguments.nil
还有一个较高级的用法,比如:

user=> (def f (fn [x y] (+ x y)))#'user/fuser=> (map f [2 4] [9 0])(11 4)

这里f函数接受两个参数,因此map 后面的集合数目必须是两个。运行的结果应该是:

((f(2 9)) (f(4 0)))

也就是(11 4)


这个map和map reduce思想有点接近。




原创粉丝点击