Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure- why doesn't this piece of code work in clojure, is there some lazy evaluation gotcha I am missing?

Am new to clojure and learning it by working through SICP.

I cannot get this piece of code from SCIP 1.3.1 to work.

What am I missing ?

(defn sum [term a next b] 
  (if (> a b) 
      0
      (+ (term a) (sum term (next a) next b))))

(defn sum-cubes-new [a b]
  ((sum cube a inc b)))

HERE is the error message:

java.lang.Integer cannot be cast to clojure.lang.IFn
  [Thrown class java.lang.ClassCastException]

Restarts:
 0: [ABORT] Return to SLIME's top level.

Backtrace:
  0: user$sum_cubes_new__2868.invoke(summation.clj:33)
  1: user$eval__2874.invoke(NO_SOURCE_FILE:1)
  2: clojure.lang.Compiler.eval(Compiler.java:4642)
  3: clojure.core$eval__5236.invoke(core.clj:2017)
  4: swank.commands.basic$eval_region__910.invoke(basic.clj:40)
  5: swank.commands.basic$eval_region__910.invoke(basic.clj:31)
  6: swank.commands.basic$eval__930$listener_eval__932.invoke(basic.clj:54)
  7: clojure.lang.Var.invoke(Var.java:359)
  8: user$eval__2871.invoke(NO_SOURCE_FILE)
  9: clojure.lang.Compiler.eval(Compiler.java:4642)
 10: clojure.core$eval__5236.invoke(core.clj:2017)
 11: swank.core$eval_in_emacs_package__458.invoke(core.clj:58)
 12: swank.core$eval_for_emacs__536.invoke(core.clj:126)
 13: clojure.lang.Var.invoke(Var.java:367)
 14: clojure.lang.AFn.applyToHelper(AFn.java:179)
 15: clojure.lang.Var.applyTo(Var.java:476)
 16: clojure.core$apply__4370.invoke(core.clj:436)
 17: swank.core$eval_from_control__461.invoke(core.clj:65)
 18: swank.core$eval_loop__464.invoke(core.clj:70)
 19: swank.core$spawn_repl_thread__598$fn__630$fn__632.invoke(core.clj:179)
 20: clojure.lang.AFn.applyToHelper(AFn.java:171)
 21: clojure.lang.AFn.applyTo(AFn.java:164)
 22: clojure.core$apply__4370.invoke(core.clj:436)
 23: swank.core$spawn_repl_thread__598$fn__630.doInvoke(core.clj:176)
 24: clojure.lang.RestFn.invoke(RestFn.java:402)
 25: clojure.lang.AFn.run(AFn.java:37)
 26: java.lang.Thread.run(Thread.java:637)
like image 799
lordOfChaos Avatar asked Jan 25 '10 18:01

lordOfChaos


1 Answers

(defn sum-cubes-new [a b]
( (sum cube a inc b) ) )

The extra set of parens around the call to sum is causing it to attempt for evaluate the resulting number as a function.

like image 58
Arthur Ulfeldt Avatar answered Oct 18 '22 23:10

Arthur Ulfeldt