【发布时间】:2013-12-09 11:38:54
【问题描述】:
我认为有办法做到这一点 - 我只是找不到确切的语法。
我想在大小为 3 的元组列表上映射一个接受三个参数的函数。比如:
(def mylist '((1 2 3)(3 4 5)))
(defn myfunc [a b c] (println "this is the first value in this tuple: " a))
(map myfunc mylist)
谁能给我准确的语法?
【问题讨论】:
我认为有办法做到这一点 - 我只是找不到确切的语法。
我想在大小为 3 的元组列表上映射一个接受三个参数的函数。比如:
(def mylist '((1 2 3)(3 4 5)))
(defn myfunc [a b c] (println "this is the first value in this tuple: " a))
(map myfunc mylist)
谁能给我准确的语法?
【问题讨论】:
您只需要其中的一对方括号来解构嵌套的列表元素。
(defn myfunc
[[a b c]]
(println "this is the first value in this tuple: " a))
但是请注意,因为map 返回一个惰性序列,所以您可能不会得到您想要的副作用,除非您使用doall 强制评估序列,或检查序列REPL。
文档:http://clojure.org/special_forms#Special Forms--Binding Forms (Destructuring)
【讨论】:
d11wtq's answer 是一个非常好的方法,它是正确的方法,除非你已经有一个你想要映射的函数。
所以,如果myfunc 是外部函数,最好使用apply 而不是编写额外的包装器:
(map (partial apply myfunc) mylist)
【讨论】: