Clojure柯里化技术细节:三角形面积代码执行报错原因解析
Let's break down exactly what's causing this error in your Clojure code. The key issue is buried in how you've defined your curry function—specifically the innermost line:
(fn [c] ((area-of-triangle a b c)))
Look at those extra outer parentheses around (area-of-triangle a b c)—that's where the bug lives.
When you call area-of-triangle a b c, it does exactly what you expect: calculates the triangle area and returns a Double value. But wrapping that result in another set of parentheses tells Clojure: "Treat this value as a function and invoke it with no arguments." Since java.lang.Double doesn't implement Clojure's IFn interface (the requirement for all callable functions in Clojure), the runtime throws a ClassCastException—it can't convert a plain number to a function.
The Simple Fix
Just remove those unnecessary outer parentheses in the innermost function of your curry definition:
(defn curry [a] (fn [b] (fn [c] (area-of-triangle a b c)))) ; No extra parentheses here
Now let's test the corrected code in the REPL:
(def a (curry 3)) (def b (a 4)) (def c (b 54.7)) ; c will now hold the correct area value (~4.896) instead of throwing an error
A Quick Clojure Parentheses Reminder
In Clojure, parentheses aren't just for grouping expressions—they have a strict meaning: "invoke whatever is inside as a function." So whenever you see a ClassCastException about converting a non-IFn type (like Double, String, or keyword) to IFn, the first thing to check is: did you accidentally wrap a non-function value in parentheses, trying to call it like a function?
内容的提问来源于stack exchange,提问作者Alex

