在Clojure中使用"apply"函数时出错:"不知道如何从:java.lang.Long创建ISeq"

dtg*_*dtg 5 exception clojure first-class-functions higher-order-functions

在"Clojure in Action"中进行以下示例(p.63):

(defn basic-item-total [price quantity] 
    (* price quantity))

(defn with-line-item-conditions [f price quantity] 
    {:pre [(> price 0) (> quantity 0)]
     :post [(> % 1)]} 
    (apply f price quantity))
Run Code Online (Sandbox Code Playgroud)

评估REPL:

(with-line-item-conditions basic-item-total 20 1)
Run Code Online (Sandbox Code Playgroud)

结果抛出以下异常:

Don't know how to create ISeq from: java.lang.Long
  [Thrown class java.lang.IllegalArgumentException]
Run Code Online (Sandbox Code Playgroud)

在评估应用程序后,似乎抛出了异常.

Bey*_*mor 8

最后一个参数apply应该是一系列参数.在您的情况下,使用可能看起来更像这样:

(defn with-line-item-conditions [f price quantity] 
    {:pre [(> price 0) (> quantity 0)]
     :post [(> % 1)]} 
    (apply f [price quantity]))
Run Code Online (Sandbox Code Playgroud)

apply在处理参数列表时非常有用.在您的情况下,您可以简单地调用该函数:

(defn with-line-item-conditions [f price quantity] 
    {:pre [(> price 0) (> quantity 0)]
     :post [(> % 1)]} 
    (f price quantity))
Run Code Online (Sandbox Code Playgroud)

  • 是的,一些doc字符串可能非常不透明.[cheatsheet](http://clojure.org/cheatsheet)是一个很好的地方,例如用法. (2认同)