【问题标题】:Clojure: How to pass parameters when reducing over functionsClojure:减少函数时如何传递参数
【发布时间】:2014-10-20 00:56:59
【问题描述】:

从http://www.braveclojure.com/functional-programming/ 开始,以下代码将修剪空白并将“lol”替换为“LOL”。

(require '[clojure.string :as s])
(defn clean
  [text]
  (s/replace (s/trim text) #"lol" "LOL"))

(clean "My boa constrictor is so sassy lol!  ")
; => "My boa constrictor is so sassy LOL!" 

现在,根据网站,下面的 reduce over 函数的代码与我们上面的代码相同。

(defn clean
      [text]
      (reduce (fn [string string-fn] (string-fn string))
              [s/trim #(s/replace % #"lol" "LOL")]))

问题:我不明白text 参数是如何传递到reduce 函数中的匿名函数的。如何编写类似的代码,将参数text 显式传递给reduce 函数中的匿名函数?

【问题讨论】:

  • 这似乎不正确。
  • @ntalbs 如果 text 是函数向量之前的 arg,它将起作用。
  • 我对这个问题做了更多的描述。请不要投反对票。 @noisesmith 我已经尝试在函数向量之前添加text。它没有工作
  • 好的。我犯了一个愚蠢的错误。我忘了先实现(require '[clojure.string :as s])。这就是为什么它不起作用。很抱歉造成混乱

标签: clojure


【解决方案1】:

reduce 函数接受一个可选参数,即归约的初始值。如果未提供,则使用最后一个 arg 的第一项(当然,在这种情况下根本不起作用,但是当您有一系列与初始值具有相同有效类型的输入时,它确实有效)。

user> (defn clean
        [text]
        (reduce (fn [string string-fn] (string-fn string))
                text
                [clojure.string/trim #(clojure.string/replace % #"lol" "LOL")]))
#'user/clean
user> (clean "My boa constrictor is so sassy lol!  ")
"My boa constrictor is so sassy LOL!"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多