r/programming • • 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

1.3k comments sorted by

View all comments

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:

(apply + [ 1 42 8675309 ]) => 8675352 ; #1 (for and while makes no sense here)

(interleave [ :a :b :c ] [ 1 2 3 ]) => (:a 1 :b 2 :c 3) ; #2

Edit2: Oh right and if lib func interleave is cheating there's also a basic sequence manipulation way to do #2:

(mapcat vector [ :a :b :c ] [ 1 2 3 ])

2

u/LazinCajun May 09 '15

It is really cool! There are applications of basically the same idea to dynamic programming in lazy functional languages too.

1

u/Godd2 May 10 '15

I love interleave. It's probably my favorite sequence-manipulating function in Clojure.

We sort of have it in Ruby, but it doesn't deal with the edge cases the same way, an it makes an array of arrays, instead of a flat list or array, so you have to flatten it.

['a', 'b', 'c'].zip([1, 2, 3]).flatten
=> ['a', 1, 'b', 2, 'c', 3]

1

u/greenthumble May 10 '15

Funny you mention that, my first clojure solution needed flatten too. It used mapv which does exactly what zip is doing there, [ ['a' '1'] ['b' '2'] ['c' '3']] heh. Then someone in IRC pointed out interleave and also mapcat. There are so many cool sequence manipulations that put other languages to shame. The only thing I'm missing from the procedural world is Python's sub-array syntax e.g. a[:-4] it's so amazingly terse. Clojure is a bit more verbose in that department heh.

1

u/Godd2 May 10 '15

Yes it's more terse, but the tradeoff is that it's inconsistent syntax. Which is fine and aesthetic in its own right, but remember, in Clojure, once you get a feel for things, it's easy to make your own like this:

(defn butlastn [n coll]
  (if (= n 1)
    (butlast coll)
    (butlastn (- n 1) (butlast coll))))
(butlastn 4 [1 2 3 4 5 6 7])
=> (1 2 3)