【问题标题】:Passing a list of functions to 'map' in clojure gives nil将函数列表传递给 clojure 中的“map”会给出 nil
【发布时间】:2019-03-06 12:12:57
【问题描述】:

我正在尝试一些 clojure 的示例。

(def sum #(reduce + %))

(def avg #(/ (sum %) (count %)))

(defn stats
  [numbers]
  (map #(% numbers) '(sum, avg)) ;;works when it is [sum avg]
  )

当我调用统计函数时

 (stats [1 24  235 34511 0 14])

它返回(nil nil)。但是,如果我按照注释中提到的那样更改代码,它会返回预期的输出。

(34785 11595/2)

为什么函数不能作为列表传递?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    您可以将集合参数中的函数传递给map,但您示例中的' 前缀是引用列表,因此内容是符号 sumavg 而不是

    '(sum avg)     ;; quoted list, contents are symbols
    '[sum avg]     ;; quoted vector, contents are symbols
    (list sum avg) ;; list of the functions, using `list` fn to create a list
    [sum avg]      ;; vector of the functions
    

    'quote 的简写。

    未加引号的列表文字被特殊处理。 Clojure 将不带引号的列表文字解释为调用,其中列表中的第一个元素指的是被调用的内容。例如,这将调用sum 函数,将avg 函数作为其第一个参数传递(这不起作用):

    (sum avg)
    

    通过mapping type 函数对带引号和不带引号的列表,我们可以看到列表元素类型的差异:

    user=> (map type '(conj assoc))
    (clojure.lang.Symbol clojure.lang.Symbol)          ;; symbols
    user=> (map type (list conj assoc))
    (clojure.core$conj__5112 clojure.core$assoc__5138) ;; fn values
    

    这是另一个关于引用的广泛答案:Using quote in Clojure

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 2015-07-19
      相关资源
      最近更新 更多