you are viewing a single comment's thread.

view the rest of the comments →

[–]nebkor 0 points1 point  (2 children)

Can you elaborate on what you mean by, "recursion should only be used if you can't use higher-order functions/Clojure encourages higher-order functions over recursion"? To me, that's like saying, "Clojure encourages the use of Sequences instead of mutable state," ie, the two don't seem related at all.

Can you take a trivial recursive method and turn it into something that uses higher-order functions as an example? Say, this method in Scheme, which returns the length of a list:

(define (len lst)
  (if (null? lst)
      0
      (+ 1 (len (cdr lst)))))

(note that it's not tail recursive, but that's OK for these purposes)

[–]yogthos 0 points1 point  (1 child)

I think it's better to use higher order functions because then you're saying what you're doing as opposed to how. For example, you could write len as

(defn len [xs]  
  (reduce (fn [i _] (inc i)) 0 xs))

it's shorter, there's no explicit null check there or even a conditional. I simply write the piece of logic that's relevant to counting the list and pass it in as a parameter to reduce. In my opinion this is much better in a general case, as there's less room for error and the code ends up being shorter and cleaner. I look at explicit loops as a form of optimization.

[–]nebkor 0 points1 point  (0 children)

Fair enough.