r/programming • u/SilasX • May 09 '15
"Real programmers can do these problems easily"; author posts invalid solution to #4
https://blog.svpino.com/2015/05/08/solution-to-problem-4
3.1k
Upvotes
r/programming • u/SilasX • May 09 '15
1
u/greenthumble May 09 '15 edited May 09 '15
3 was easy but I had never coded it up before so decided to take a look at how I would do it in Clojure. My solution was alright, basic top down type recursion that built up the array at each step with a little extra trick called "trampoline" applied so the function doesn't get all stack-smashy and using the +' operator which uses BigInt. Then I saw this:
http://en.wikibooks.org/wiki/Clojure_Programming/Examples/Lazy_Fibonacci#Recursive_Version
Which leads directly to this:
http://en.wikipedia.org/wiki/Corecursion
Wow. I've been doing this a looooong time and Clojure keeps teaching me new things. Like there's a whole different way to think about recursion.
That Clojure example is doing the extremely neat trick of defining the array in terms of itself - the array equals the array plus the array shifted (using "rest" to shift, self-referentiation, and lazy evaluation).
Edit: Oh yeah heh also #1 and 2 are ridiculously simple in Clojure:
Edit2: Oh right and if lib func interleave is cheating there's also a basic sequence manipulation way to do #2: