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

Show parent comments

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)