Error using "apply" function in Clojure: "Don't know how to create ISeq from: java.lang.Long"
Asked Answered
O

1

5

Working on the following example in "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))

Evaluating on the REPL:

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

Results in the following exception being thrown:

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

It appears the exception is being thrown after the apply procedure is evaluated.

Oxidase answered 24/8, 2012 at 4:56 Comment(1)
apply is a function, not a macro.Cam
I
8

The last argument to apply is supposed to be a sequence of arguments. In your case, the usage might look more like this:

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

apply is useful when you're working with a list of arguments. In your case, you can simply call the function:

(defn with-line-item-conditions [f price quantity] 
    {:pre [(> price 0) (> quantity 0)]
     :post [(> % 1)]} 
    (f price quantity))
Insider answered 24/8, 2012 at 5:25 Comment(2)
Thanks - I see now that in the case of the apply macro, the sequence should be a vector. This was not clear after reading the description after evaluating (doc apply): "Applies fn f to the argument list formed by prepending intervening arguments to args."Oxidase
Yeah, some of the doc strings can be pretty opaque. The cheatsheet is a great place for example usages.Insider

© 2022 - 2024 — McMap. All rights reserved.