使用常量参数将函数应用于集合的元素

时间:2013-01-08 10:36:08

标签: clojure

  

可能重复:
  Mapping over sequence with a constant

我正在尝试执行以下操作(仅作为示例):

(defn f [x param] ( 
  ; do something with "x" AND with "param"
  ))
(defn filtered-list [param] (map f ["a" "b" "c"]))
; called later as
(filtered-list 123)
; expected calls are: (f "a" 123), (f "b" 123) and (f "c" 123)

因此,我需要找到一种方法将param传递给f,由map使用。 Clojure有可能吗?此功能也可称为"functional closure"

2 个答案:

答案 0 :(得分:2)

使用partial从f创建一个curried函数,传递param

(defn f [param x] ( 
  ; do something with "x" AND with "param"
  ))

(defn filtered-list [param] (map (partial f param) ["a" "b" "c"]))

答案 1 :(得分:1)

如何使用partial

(defn f [param x]  
    (str param \- x) ;; do something
)

(defn filtered-list 
    [param] 
    (map (partial f param) ["a" "b" "c"]))

但是,您必须更改f的参数顺序。