【问题标题】:How can a list or vector in Clojure be used to store and use functions?Clojure 中的列表或向量如何用于存储和使用函数?
【发布时间】:2021-09-28 17:58:52
【问题描述】:

这是我在 REPL 中尝试过的。

(def mstuffs [(fn [n] (* 1 n)) (fn [n] (* 1 n))])
((mstuffs first) 2)

这是我得到的错误

; Execution error (IllegalArgumentException) at nrepl.middleware.interruptible-eval/evaluate$fn$fn (interruptible_eval.clj:87).
; Key must be integer

我做错了什么?

【问题讨论】:

    标签: function collections clojure


    【解决方案1】:

    clojure 中的向量是从索引到相应项目的函数,例如

    ([:foo :bar :baz] 1)
    => :bar
    

    所以(mstuffs first) 正在尝试使用参数first 索引向量mstuffs。由于first 是一个函数而不是整数,因此您会得到异常。看起来你的意思是调用向量中的第一个函数,所以应该使用

    ((first mstuffs) 2)
    

    【讨论】:

    • 谢谢!男孩,我现在觉得很傻。我已经盯着它太久了。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2018-12-19
    • 1970-01-01
    相关资源
    最近更新 更多