2

Preface Firstly, I'm new to Clojure and programming, so I thought I'd try to create a function that solves a non-trivial equation using my natural instincts. What resulted is the desire to find a square root.

The question What's the most efficient way to stop my square-n-map-maker function from iterating past a certain point? I'd like to fix square-n-map-maker so that I can comment out the square-maker function which provides me with the results and format I currently want to see but not the ability to recall the square-root answer (insofar as I know).

I.e. I want it to stop when it is greater than or equal to my input value

My initial thought was that instead of a keyword list, I would want it to be a map. But I'm having a very difficult time getting my function to give me a map. The whole reason I wanted a map where one member of a pair is n and another is n^2 so that I could extract the actual square root from it and it give it back to the user as the answer.

Any ideas on the best way to accomplish this? (below is the function I want to fix)

;; attempting to make a map so that I can comb over the 
;; map later and recall a value that meets
;; my criteria to terminate and return result if (<= temp-var input)

(defn square-n-map-maker [input] (for [temp-var {remainder-culler input}]
                                   (map list(temp-var) (* temp-var temp-var))
                                 )
)
(square-n-map-maker 100) => clojure.lang.ArityException: Wrong number of args (0) passed to: MapEntry
         AFn.java:437 clojure.lang.AFn.throwArity
          AFn.java:35 clojure.lang.AFn.invoke

/Users/dbennett/Dropbox/Clojure Files/SquareRoot.clj:40 sqrt-range-high-end/square-n-map-maker[fn]

The following is the rest of my code

;; My idea on the best way to find a square root is simple.
;; If I want to find the square root of n, divide n in half
;; Then find all numbers in 0...n that return only a remainder of 0.
;; Then find the number that can divide by itself with a result of 1.
;; First I'll develop a function that works with evens and then odds
(defn sqrt-range-high-end [input] (/ input 2))
(sqrt-range-high-end 100) => 50

(defn make-sqrt-range [input] (range (sqrt-range-high-end (+ 1 input))))
(make-sqrt-range 100) =>(0 1 2 3 4 5 6 ... 50)    
(defn zero-culler [input] (remove zero? (make-sqrt-range input)))
(zero-culler 100) =>(1 2 3 4 5 6 ... 50) 

(defn odd-culler [input] (remove odd? (zero-culler input)))
(odd-culler 100) => (2 4 6 8 10...50)    

(defn even-culler [input] (remove even? (zero-culler input)))
(even-culler 100) => (1 3 5 7...49)

(defn remainder-culler [input] (filter #(zero? (rem input %)) (odd-culler input)))
(remainder-culler 100) => (2 4 6 12 18)

(defn square-maker [input] (for [temp-var (remainder-culler input)]
                           (list (keyword (str
                                             temp-var" "
                                             (* temp-var temp-var)
                                           )
                                 )
                           )
                       )
(square-maker 100) => ((:2 4) (:4 16) (:10 100) (:20 400) (:50 2500))
dmbennett
  • 109
  • 1
  • 8

2 Answers2

4

Read the Error Messages!

You're getting a little ahead of yourself! Your bug has nothing to do with getting for to stop "looping."

(defn square-n-map-maker [input] (for [temp-var {remainder-culler input}]
                                   (map list(temp-var) (* temp-var temp-var))))
(square-n-map-maker 100) => clojure.lang.ArityException: Wrong number of args (0) passed to: MapEntry
          AFn.java:437 clojure.lang.AFn.throwArity
          AFn.java:35 clojure.lang.AFn.invoke

Pay attention to error messages. They are your friend. In this case, it's telling you that you are passing the wrong number of arguments to MapEntry (search for IPersistentMap). What is that?

{} creates a map literal. {:key :value :key2 :value2} is a map. Maps can be used as if they were functions:

 > ({:key :value} :key)
 :value

That accesses the entry in the map associated with key. Now, you created a map in your first line: {remainder-culler input}. You just mapped the function remainder-culler to the input. If you grab an item out of the map, it's a MapEntry. Every MapEntry can be used as a function, accepting an index as an argument, just like a Vector:

> ([:a :b :c :d] 2)
:c

Your for is iterating over all MapEntries in {remainder-culler input}, but there's only one: [remainder-culler input]. This MapEntry gets assigned to temp-var.

Then in the next line, you wrapped this map in parentheses: (temp-var). This forms an S-expression, and expressions are evaluated assuming that the first item in the expression is a function/procedure. So it expects an index (valid indices here would be 0 and 1). But you pass no arguments to temp-var. Therefore: clojure.lang.ArityException: Wrong number of args.

Also, note that map is not a constructor for a Map.

Constructing a map

Now, on to your problem. Your square-maker is returning a list nicely formatted for a map, but it's made up of nested lists.

Try this:

(apply hash-map (flatten (square-maker 100)))

Read this page and this page to see how it works.

If you don't mind switching the order of the keys and values, you can use the group-by that I mentioned before:

(defn square-maker [input]
    (group-by #(* % %) (remainder-culler input)))
(square-maker 100) => {4 [2], 16 [4], 100 [10], 400 [20], 2500 [50]}

Then you can snag the value you need like so: (first ((square-maker 100) 100)). This uses the map-as-function feature I mentioned above.

Loops

If you really want to stick with the intuitive looping concept, I would use loop, not for. for is lazy, which means that there is neither means nor reason (if you use it correctly) to "stop" it -- it doesn't actually do any work unless you ask for a value from it, and it only does the work it must to give you the value you asked for.

(defn square-root [input]
    (let [candidates (remainder-culler input)]
         (loop [i 0]
            (if (= input (#(* % %) (nth candidates i)))
                (nth candidates i)
                (recur (inc i))))))

The embedded if determines when the looping will cease.

But notice that loop only returns its final value (acquaint yourself with loop's documentation if that sentence doesn't make sense to you). If you want to build up a hash-map for later analysis, you'd have to do something like (loop [i 0, mymap {}] .... But why analyze later if it can be done right away? :-)

Now, that's a pretty fragile square-root function, and it wouldn't be too hard to get it caught in an infinite loop (feed it 101). I leave it as an exercise to you to fix it (this is all an academic exercise anyway, right?).

I hope that helps you along your way, once again. I think this is a great problem for learning a new language. I should say, for the record, though, that once you are feeling comfortable with your solution, you should search for other Clojure solutions to the problem and see if you can understand how they work -- this one may be "intuitive," but it is not well-suited to Clojure's tools and capabilities. Looking at other solutions will help you grasp Clojure's world a bit better.

For more reading:

Imperative looping with side-effects.

How to position recur with loop

The handy into

Finally, this "not constructive" list of common Clojure mistakes

Community
  • 1
  • 1
galdre
  • 2,319
  • 17
  • 31
2

for is not a loop, and it's not iterating. It lazily creates a list comprehension, and it only realizes values when required (in this case, when the repl tries to print the result of the evaluation). There are two usual ways to do what you want: one is to wrap square-maker in

(first (filter some-predicate (square-maker number))) to obtain the first element in the sequence that complies with some-predicate. E.g.

(first (filter #(and (odd? %) (< 50 %)) (range))) => 51

The above won't realize the infinite range, obviously.

The other one is not to use a list comprehension and do it in a more imperative way: run an actual loop with a termination condition (see loop and recur).

Example:

(loop [x 0]
  (if (and (odd? x) (> x 50))
    x
    (recur (inc x))))
Diego Basch
  • 12,764
  • 2
  • 29
  • 24