0

I am lost with the following code trying to calculate square roots. The code is:

(defn tempsqrt [x p i]
  (if (< i 2) 
    p
    (tempsqrt x (+ (/ x (* 2 p)) (/ p 2)) (- i 1))))

(defn mysqrt [x]
  (let  [i 10 
         p (/ x 5)]
    (tempsqrt x p i)))

When I execute (msqrt 1) in Counterclockwise, it seems I get an endless loop since I have to forcibly stop processing. I have tried to output i and p in mysqrt and they seem to be calculated fine, I think there must be some stupid problem somewhere but I can't manage to find it.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • Possibly a typo - your function name is `mysqrt` but the function you're invoking is `msqrt`. ??? I'm thinking it must be something like this because you're invoking `tempsqrt` recursively instead of using `recur` to force a tail-call, so *if* `tempsqrt` was being invoked in an infinite recursive loop your stack would blow chunks all over your monitor. (Lovely thought, eh? :-) So clearly (at least clearly in my mind) `tempsqrt` isn't being invoked. I could, of course, be wrong - but I tried your code and it worked fine for me. Best of luck. – Bob Jarvis - Слава Україні Aug 07 '16 at 04:27
  • I must have been some sort of typo, I have rewritten everything and now it magically works. Thanks everyone! – user263416 Aug 07 '16 at 08:42

1 Answers1

0

Works as expected on my machine.

boot.user=> (defn mysqrt [x]
       #_=>   (let  [i 10
       #_=>         p (/ x 5)]
       #_=>   (tempsqrt x p i)))
#'boot.user/mysqrt
boot.user=> (defn tempsqrt [x p i]
       #_=>   (println i)
       #_=>   (if (< i 2) p
       #_=>       (tempsqrt x (+ (/ x (* 2 p)) (/ p 2)) (- i 1))))
#'boot.user/tempsqrt
boot.user=> (mysqrt 1)
10
9
8
7
6
5
4
3
2
1
19323349832288915105454068722019581055401465761603328550184537628902466746415537000017939443193837284332679428868611117710999636580698761476491418202290083264324580207274376284652360489310800028152901586154293130345674316605555829428921442625537/19323349832288915105454068722019581055401465761603328550184537628902466746415537000017939416378221424447485229720561121299307381621967120291704662755167195820796520060180422680903764155503944648089185213182191422837908692712415936561623430457345
Michiel Borkent
  • 34,228
  • 15
  • 86
  • 149
  • Thank you for the provided information, I have restarted Counterclockwise and REPL here and still, the output just stops even if I type new functions in, I get no replies. Nothing in logs, nowhere ...I have to click "forcibly stop the current running evaluation" and then it moves forward ... – user263416 Aug 06 '16 at 13:18