Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would probably write something like this in Haskell, using the <code>Data.List.Split</code> package from Hackage:</p> <pre><code>import Data.List (intercalate, transpose) import Data.List.Split (splitEvery) data Direction = Horizontal | Vertical deriving (Eq, Read, Show) table :: Direction -&gt; Int -&gt; [a] -&gt; [[a]] table Horizontal cols xs = splitEvery cols xs table Vertical cols xs = let (q,r) = length xs `divMod` cols q' = if r == 0 then q else q+1 in transpose $ table Horizontal q' xs showTable :: Show a =&gt; [[a]] -&gt; String showTable = intercalate "\n" . map (intercalate "\t" . map show) main :: IO () main = mapM_ putStrLn [ showTable $ table Horizontal 3 [0..9] , "---" , showTable $ table Vertical 3 [0..9] ] </code></pre> <p>Some of this, like the <code>Direction</code> type and the <code>transpose</code> trick, was derived from jkramer's answer. I wouldn't use keyword arguments for something like this in Haskell (it doesn't really have such things, but you can emulate them using records as in Edward Kmett's answer), but I put those arguments first because it's more useful with partial application (<code>defaultTable = table Horizontal 1</code>). The <code>splitEvery</code> function just chunks a list into lists of the appropriate size; the rest of the code should be straightforward. The <code>table</code> function returns a list of lists; to get a string, the <code>showTable</code> function inserts tabs and newlines. (The <code>intercalate</code> function concatenates a list of lists, separating them with the given list. It's analogous to Perl/Python/Ruby's <code>join</code>, only for lists instead of just strings.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload