Friday, September 14, 2012

Better understanding Clojure recur

Just playing around with recur more. I really didn't like the example they had online. After digging around some, I got the idea behind recur, it recalls the function it directly sits under. Mostly I see it used in loops in the examples online, however the = function we were looking at yesterday didn't. It was just calling the normal function it was in.

Quick warning, the first couple of examples won't have a way to stop them. I'm running them in repl, and CTRL+C to stop them. I felt that this best explains what recur is doing.

(defn recur-test 
  [message] 
  (println message) 
  (recur message)
)

user=>(recur-test "rawr")
rawr
rawr
rawr
...
(defn recur-test 
  [message count]
  (println (format "%s: %s" message count))
  (recur message (inc count))
)

user=>(recur-test "rawr" 0)
rawr: 0
rawr: 1
rawr: 2
rawr: 3
...

Let's add the if check into the function so we don't have to keep CTRL+C our repl.

(defn recur-test 
  [message count]
  (println (format "%s: %s" message count))
  (if (< count 5)
    (recur message (inc count))
  )
)

user=> (recur-test "rawr" 0)
rawr: 0
rawr: 1
rawr: 2
rawr: 3
rawr: 4
rawr: 5
nil

It becomes pretty apparent what recur is and is doing at this point. Now when we look at the examples on recur in the docs, it makes more sense for those who haven't seen it before: recur docs

No comments: