How would you write this Clojure snippet in Ruby and/or Haskell?

Posted by dnolen on Stack Overflow See other posts from Stack Overflow or by dnolen
Published on 2010-05-12T14:20:42Z Indexed on 2010/05/12 15:24 UTC
Read the original article Hit count: 152

Filed under:
|
|

I was working on a Rails template and was trying to write a bit of code that allows me to populate a table or multiple columns of ul tags "top-to-bottom" and "left-to-right" across however many columns I specify. I'm just getting the hang of Ruby so I couldn't figure this out. I'm also curious about an idiomatic Haskell version for this useful snippet. Improvements to Clojure version appreciated:

(defn table [xs & {:keys [cols direction]
                   :or   {cols 1 direction 'right}}]
  (into []
        (condp = direction
          'down (let [c (count xs)
                      q (int (/ c cols))
                      n (if (> (mod c q) 0) (inc q) q)]
                  (apply map vector (partition n n (repeat nil) xs)))
          'right (map vec (partition cols cols (repeat nil) xs))))) 

With this bit of code I can then do the following:

(table (range 10) :cols 3)

Printed out this would look like so:

0    1    2 
3    4    5 
6    7    8
9

And the trickier one:

(table (range 10) :cols 3 :direction 'down)

Looks like so:

0    4    8    
1    5    9    
2    6        
3    7        

© Stack Overflow or respective owner

Related posts about clojure

Related posts about ruby