我正在开发一个Rails模板,尝试编写一些代码,使我能够填充一个表格或多个ul标签的多列。我想让它从上到下、从左到右地填充任意数量的列。由于我刚开始学习Ruby,所以无法解决这个问题。我也想知道如何用Haskell完成这个实用的代码片段。请提供对Clojure版本的改进建议:
(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)))))
使用这段代码后,我可以进行以下操作:
(table (range 10) :cols 3)
打印出来的结果应该如下所示:
0 1 2
3 4 5
6 7 8
9
还有一个更棘手的问题:
(table (range 10) :cols 3 :direction 'down)
看起来像这样:
0 4 8
1 5 9
2 6
3 7