【问题标题】:Error using "apply" function in Clojure: "Don't know how to create ISeq from: java.lang.Long"在 Clojure 中使用“应用”函数时出错:“不知道如何从:java.lang.Long 创建 ISeq”
【发布时间】:2012-08-24 04:56:59
【问题描述】:

在“Clojure in Action”(第 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))

在 REPL 上进行评估:

(with-line-item-conditions basic-item-total 20 1)

导致以下异常被抛出:

Don't know how to create ISeq from: java.lang.Long
  [Thrown class java.lang.IllegalArgumentException]

似乎在评估应用程序后引发了异常。

【问题讨论】:

  • apply 是一个函数,而不是宏。

标签: exception clojure higher-order-functions first-class-functions


【解决方案1】:

apply 的最后一个参数应该是sequence of arguments。在您的情况下,用法可能看起来更像这样:

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

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

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

【讨论】:

  • 谢谢 - 我现在看到在应用宏的情况下,序列应该是一个向量。评估后阅读描述后不清楚这一点(doc apply):“将 fn f 应用于通过将干预参数添加到 args 形成的参数列表。”
  • 是的,一些文档字符串可能非常不透明。 The cheatsheet 是示例用法的好地方。
猜你喜欢
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多