Clojure: Using take-while With iterate Instead of loop and recur
I just discovered the take-while
and iterate
pattern in Clojure after looking at this solution to the Clojure Collatz Conjecture exercise on the Exercism site. I really like the following about it:
- It seems very concise and elegant
- When you are working with mathematical formulae in a program you might find yourself “reformatting” it to fit into a loop or recursion pattern. This pattern seems to make it easy to externalize your formula and then mix it in using higher-order functions.
At this point I wish I could show you simple, short examples of how to convert a Clojure function that uses the loop
and recur
pattern with one that uses take-while
and iterate
. But I have been unsuccessful at wrapping my head around the pattern after about 30 minutes of trying. So instead, I’m mentioning it here so I can “keep it on my radar”.
I’m trying to code in Clojure at least a little every day, and Exercism has made that very easy and rewarding. Hopefully after I get a little farther in the syllabus I can start to understand how this pattern works.