Re: easy sum of squares refactor question

2011-10-31 Thread Aquahappy
Thanks so much for your help!!! I'm so glad you had the time to respond to my newbie question. And as if you read my mind as I was going through the SICP lecture and referencing chapter two in Manning's Joy of Clojure book I was wondering how to turn this explicit recursive call taken from the

Re: easy sum of squares refactor question

2011-10-31 Thread nchurch
Glad I could help! SICP is a wonderful book, and Clojure is a dream come true in that it gives you a step from SICP into the real world. Clojure would be just about perfect if it had general tail call optimization and continuations, but I don't really miss those so far (in any case they can't

easy sum of squares refactor question

2011-10-30 Thread Aquahappy
Hi All, I'm watching Brian Harvey's SICP lecture #3 from Berkeley 61A/Spring 2011 and had a question about how I could refactor the following function so that the (+a 1) can be abstracted to be a function and passed in. Here is the original: (defn square [x] (* x x)) (defn sum [fn a b] (if

Re: easy sum of squares refactor question

2011-10-30 Thread nchurch
All you have to do is abstract the function you want (by 'abstract' I mean put it in the argument list and replace the function with the variable): (defn sum2 [func incr a b] (if ( a b) 0 (+ (fn a) (sum2 func incr (incr a) b You wouldn't want to use this code in the real world

Re: easy sum of squares refactor question

2011-10-30 Thread nchurch
Another solution, this time using Clojure's tail recursion: (defn sum2 [func incr a b] (loop [accum 0 x a] (if ( x b) accum (recur (+ (func x) accum) (incr x) This may be getting ahead of where you are now, so come back and look when you've covered map, reduce, and