Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I liked the task, so I wrote an alternative solution.</p> <p>We could build it up, a bit like you would with a pretty printer. Look into the <a href="http://hackage.haskell.org/package/pretty/" rel="noreferrer">pretty</a> package to take these ideas and use them properly, but let's stick to plain old <code>[String]</code> for this.</p> <p>First let's make a blank grid</p> <pre><code>blank :: Int -&gt; [String] blank n = replicate (3^n) $ replicate (3^n) ' ' </code></pre> <p>Then let's define a diamond.</p> <pre><code>diamond :: Int -&gt; [String] diamond 0 = ["*"] diamond n = let o = diamond (n-1) x = blank (n-1) in joinMatrix [[x,o,x] ,[o,x,o] ,[x,o,x]] </code></pre> <p>But how can we join this matrix of <code>[String]</code> together? First get all the <code>String</code>s that should be concatenated together next to each other instead of under each other using <code>transpose</code>, then <code>concat</code> them all:</p> <pre><code>joinLine :: [[String]] -&gt; [String] joinLine = map concat.transpose </code></pre> <p>To do that to a whole matrix we need to join the lines on each row, then concat all the lines together into one list of lines:</p> <pre><code>joinMatrix :: [[[String]]] -&gt; [String] joinMatrix = concat.map joinLine </code></pre> <p>helper functions for printing:</p> <pre><code>put = mapM_ putStrLn d n = put $ diamond n </code></pre> <p>You could argue that the numerical solution is more efficient, and it is, but <code>d 4</code> is the largest that fits on my screen and isn't slow. You could also argue that this solution is clearer.</p> <pre><code>*Main&gt; d 0 * *Main&gt; d 1 * * * * *Main&gt; d 2 * * * * * * * * * * * * * * * * </code></pre> <p>(It works for higher n too, but they would make this post unnecessarily long on the page.)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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