SICP sqrt NullPointerException

I came across an unexpected NullPointerException when implementing some SICP initial code in Clojure. In particular, I want to implement the iterative square root procedure from section 1.1.7.

Here is the code:

(defn square [x] (* xx)) (defn abs [x] (cond (< x 0) (- x) :else x)) (defn average [xy] (/ (+ xy) 2)) (defn sqrt ([x] (sqrt 1.0 x)) ([guess x] (letfn [(good-enough? [guess] (< (abs (- (square guess) x)) 0.001)) (improve [guess] (average guess (/ x guess)))] (if (good-enough? guess) guess (recur (improve guess) x))))) 

This works great for fairly small values, for example. (sqrt 16) . I get a NullPointerException clojure.lang.Numbers.lt (Numbers.java:3693) for any input exceeding approximately (square 2718) .

Any ideas?

Updating with all trace (the previous one is all I get in repl):

An exception is thrown in the "main" java.lang.NullPointerException thread in Clojure.lang.Numbers.lt (Numbers.javahaps693) at sicp_in_clojure.chapter_one $ sqrt $ good_enough_QMARK ___ 14.invoke (chapter_one.clj: 40) at sicp_inc__center_one sqrt.invoke (chapter_one.clj: 43) at sicp_in_clojure.chapter_one $ sqrt.invoke (chapter_one.clj: 37) at sicp_in_clojure.chapter_one $ eval19.invoke (chapter_one.clj: 48) in Clojure.lang.Compiler.al .java: 6465) in Clojure.lang.Compiler.load (Compiler.java:6902) in Clojure.lang.Compiler.loadFile (Compiler.java:6863) at Clojure.main $ load_script.invoke (main.clj: 282) at Clojure.main $ script_opt.invoke (main.clj: 342) at Clojure.main $ main.doInvoke (main.clj: 426) in Clojure.lang.RestFn.invoke (RestFn.java:408) in Clojure.lang. Var.invoke (Var.java:401) in Clojure.lang.AFn.applyToHelper (AFn.java:161) in Clojure.lang.Var.applyTo (Var.javaβˆ—18) at Clojure.main.main (main.java : 37)

+6
source share
2 answers

Not sure if this is still relevant or not, but I thought it was worth trying it with the LightTable Playground , which allows you to see how things are interpreted:

light table demo screenshot of above code

Have you tried with a recent build, say, the new Clojure 1.4.0 release?

+1
source

Hey, this worked for me. I am using clojure 1.3.0. Below is the terminal output. The code is working fine.

 [ user@myhost ~]$ clj Clojure 1.3.0 user=> (defn square [x] (* xx)) #'user/square (defn abs [x] (cond (< x 0) (- x) :else x)) #'user/abs (defn average [xy] (/ (+ xy) 2)) #'user/average (defn sqrt ([x] (sqrt 1.0 x)) ([guess x] (letfn [(good-enough? [guess] (< (abs (- (square guess) x)) 0.001)) (improve [guess] (average guess (/ x guess)))] (if (good-enough? guess) guess (recur (improve guess) x))))) #'user/sqrt user=> (sqrt 16) 4.000000636692939 user=> (sqrt 2718) 52.134441897781194 user=> (sqrt 3000) 54.77225658092904 
0
source

Source: https://habr.com/ru/post/899187/


All Articles