If statement with comparison

3725 views clojure
1

I am trying to do a comparison to find the largest number in a list. I know I could just use the (max 1 2 4 3) but I'm trying to write the function myself. However, I'm not too sure where the error is. Whenever I run this, the maximum is always 2. Am I doing a comparison wrong somewhere or forget something?

(defn maxVal [list]
  (def maxValue 0)

  (doseq [x list]
    (println x maxValue)
    (if > x maxValue)
      (do (println x ">" maxValue)
          (def maxValue x)))
    (var-get #'maxValue))

(maxVal '(1 4 3 2))

answered question

Not your immediate problem, but as an aside -- vars aren't meant to be used this way, and abusing them has some nasty side effects (they aren't designed to be particularly fast/cheap to update, for example, so there are locks involved). Stick to atoms if you need something you can alter, or better, just use loop/recur for code (like this!) that can just rebind names and doesn't need to have mutable values at all.

1 Answer

0

The problem is that your code is evaluating > as a value, not invoking it as a function.

(if > x maxValue)

...evaluates to x, because > is neither nil nor false. Consequently, the current indentation (while it reflects intent accurately) is a bit misleading; the do should be outside the if, since it takes place no matter what happened prior.

Presumably, what you instead want is:

(if (> x maxValue)

posted this

Have an answer?

JD

Please login first before posting an answer.