Clojure地图.传递函数多个参数

Nab*_*ska 1 collections dictionary functional-programming clojure

我正在寻找一种如何以更自定义的方式使用地图功能的方法.如果我想要实现的功能不同,请您告诉我.

;lets say i have addOneToEach function working as bellow

(defn plusOne[singleInt]
   (+ 1 singleInt))

(defn addOneToEach[intCollection] ;[1 2 3 4]
   (map plusOne intCollection))   ;=>(2 3 4 5)

;But in a case I would want to customly define how much to add 

(defn plusX[singleInt x]
   (+ x singleInt))

(defn addXToEach[intCollection x] ;[1 2 3 4]
   ;how do I use plusX here inside map function?
   (map (plusX  ?x?) intCollection))   ;=>((+ 1 x) (+ 2 x) (+ 3 x) (+ 4 x))
Run Code Online (Sandbox Code Playgroud)

我不是在寻找一个为集合中的每个添加x的函数,而是一种将额外的参数传递给map正在使用的函数的方法.

cfr*_*ick 8

已经提到的另一个选项是partial(请注意,在示例中,参数的顺序无关紧要,因为您只需添加它们,但是从左到右部分绑定它们,所以要小心):

user=> (doc partial)
-------------------------
clojure.core/partial
([f] [f arg1] [f arg1 arg2] [f arg1 arg2 arg3] [f arg1 arg2 arg3 & more])
  Takes a function f and fewer than the normal arguments to f, and
  returns a fn that takes a variable number of additional args. When
  called, the returned function calls f with args + additional args.
nil
user=> (defn plus-x [x i] (+ x i))
#'user/plus-x
user=> (map (partial plus-x 5) [1 2 3])
(6 7 8)
Run Code Online (Sandbox Code Playgroud)


and*_*zko 5

你几乎猜对了。

有几种可能的方式:

1.

(defn addXToEach[intCollection x]
   (map #(plusX % x) intCollection))
Run Code Online (Sandbox Code Playgroud)

#(%)意思相同(fn [x] (x))(注意x这里正在评估)。

2.

(defn addXToEach[intCollection x]
   (map (fn [item] (plusX item x)) intCollection))
Run Code Online (Sandbox Code Playgroud)

3.

(defn addXToEach[intCollection x]
   (map #(+ % x) intCollection))
Run Code Online (Sandbox Code Playgroud)

然后你不必定义你的plusX函数。

希望能帮助到你!


sch*_*eho 5

有几种方法可以解决这个问题。一种是通过以下方式使用显式本地函数letfn

(defn add-x-to-each [ints x]
 (letfn [(plus-x [i]
           (+ i x))]
   (map plus-x ints)))
Run Code Online (Sandbox Code Playgroud)

对于这一小段代码,这可能有点矫枉过正,您可以通过匿名函数简单地简化它:

(defn add-x-to-each [ints x]
  (map #(+ % x) ints))
Run Code Online (Sandbox Code Playgroud)

这两种解决方案基本上都使用了闭包,这是一个需要了解的重要概念:它归结为动态定义一个函数,该函数在定义函数时引用环境中的变量。在这里,我们推迟plus-x(或匿名)函数的创建,直到x被绑定,因此plus-x可以引用传递给 的任何值add-x-to-each


Thu*_*ail 5

你申请map一个集合,使功能map应用必须采取一个说法。问题是,这个函数是如何组成的?

功能

(defn plusOne [singleInt]
   (+ 1 singleInt))
Run Code Online (Sandbox Code Playgroud)

...工作。它也被称为inc

但是函数

(defn plusX [singleInt x]
   (+ x singleInt))
Run Code Online (Sandbox Code Playgroud)

...不起作用,因为它需要两个参数。给定一个数x,你想回到一个功能,增加了X到它的参数:

(defn plusX [x]
   (fn [singleInt] (+ x singleInt))
Run Code Online (Sandbox Code Playgroud)

您可以使用返回的功能plusXmap

当你编写这样一个函数时,你可以使用额外的参数。这种由包含捕获数据的表达式组成的函数称为闭包

例如,(plusX 3)是一个增加3其参数的函数。

(map (plusX 3) stuff)
;(4 5 6 7)
Run Code Online (Sandbox Code Playgroud)

如您所见,您无需为闭包命名。