【问题标题】:clojure reduce. no start value, empty collectionclojure 减少。无起始值,空集合
【发布时间】:2016-03-17 03:58:47
【问题描述】:

谜语中,我必须完成以下表达式才能评估为真。必须有一个插入,适合所有人。

(= 15 (reduce __ [1 2 3 4 5]))
(=  0 (reduce __ []))
(=  6 (reduce __ 1 [2 3]))

第三个表达式提供一个起始值。因此,我的替代品无法提供另一个。

这个函数将通过第一和第三个真值测试:

#(+ %1 %2)

但是,第二个表达式会产生以下错误:

clojure.lang.ArityException: 传递给 (...my function id) 的 args (0) 数量错误

看起来通常只有当起始值 + 集合的长度大于 2 时,reduce 才会调用给定函数。如果这个长度为 0,就像上面的情况一样,它也会被调用 - 使用 0 个参数。

有人提示如何在这里进行吗?

【问题讨论】:

  • 提示:(+) 的结果是什么?
  • 谢谢!当然,再简单不过了! (同时我的解决方案是:(fn [& more] (if (= (count more) 0) 0 (apply + more))) ha, ha)
  • 很高兴它有帮助,您仍然可以简化很多;) 如果您正在使用 4clojure,请不要犹豫查看其他解决方案。
  • (+) 不是平手吗?
  • 我试图在 stackoverflow 中回答我的问题,但至少有 30 个字符。太糟糕了。一个字符没有机会。

标签: clojure functional-programming


【解决方案1】:

从 cmets 看来,解决方案显然是 +,但也许有必要详细了解它以了解 为什么。事实证明,它有很多东西。

首先我们看reduce,看看有什么要求:

(defn reduce
  "f should be a function of 2 arguments. If val is not supplied,
  returns the result of applying f to the first 2 items in coll, then
  applying f to that result and the 3rd item, etc. If coll contains no
  items, f must accept no arguments as well, and reduce returns the
  result of calling f with no arguments.  ..."
  ... 
  ([f coll]
     (if (instance? clojure.lang.IReduce coll)
       (.reduce ... coll f)
       ...))
  ([f val coll]
     (if (instance? clojure.lang.IReduceInit coll)
       (.reduce ... coll f val)
       ...)))

这是一个多参数函数,它要么接受一个函数和一个集合,要么接受一个函数、初始值和一个集合。

+ 也是一个多参数函数,其行为取决于您传递给它的参数数量。下面的源代码(针对我们关心的部分进行了编辑)显示 reduce 满足 0-arity 和 2-arity。

(defn +
  "Returns the sum of nums. (+) returns 0..."
  ...
  ([] 0)
  ...
  ([x y] (. clojure.lang.Numbers (add x y)))
  ...

显然(reduce + [])调用了第一个子句并返回0。解释了测试2。

这适用于第一个测试,通过在紧密的for 循环中将 add 函数应用于每对数字 which happens in the Java internals for Clojure

最后的测试和第一个完全一样,只是它调用了reduce 的[v val coll] 实现。这适用于a slightly different internal function,但效果相同。

备注

[1]:IFnJava interface for clojure functions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2020-03-25
    • 2016-03-26
    • 2011-03-10
    相关资源
    最近更新 更多