Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Apart from the fact that <code>inits</code> and <code>tails</code> aren't found in <code>Prelude</code>, you can define your function as such:</p> <pre><code>yourFunction :: [a] -&gt; [[a]] yourFunction = filter (not . null) . concat . map inits . tails </code></pre> <p>This is what it does, step by step:</p> <ul> <li><code>tails</code> gives all versions of a list with zero or more starting elements removed: <code>tails [1,2,3] == [[1,2,3],[2,3],[3],[]]</code></li> <li><code>map inits</code> applies <code>inits</code> to every list given by <code>tails</code>, and does exactly the opposite: it gives all versions of a list with zero or more ending elements removed: <code>inits [1,2,3] == [[],[1],[1,2],[1,2,3]]</code></li> <li>I hope you already know <code>concat</code>: it applies <code>(++)</code> where you see <code>(:)</code> in a list: <code>concat [[1,2],[3],[],[4]] == [1,2,3,4]</code>. You need this, because after <code>map inits . tails</code>, you end up with a list of lists of lists, while you want a list of lists.</li> <li><code>filter (not . null)</code> removes the empty lists from the result. There will be more than one (unless you use the function on the empty list).</li> </ul> <p>You could also use <code>concatMap inits</code> instead of <code>concat . map inits</code>, which does exactly the same thing. It usually also performs better.</p> <hr> <p>Edit: you can define this with <code>Prelude</code>-only functions as such:</p> <pre><code>yourFunction = concatMap inits . tails where inits = takeWhile (not . null) . iterate init tails = takeWhile (not . null) . iterate tail </code></pre>
 

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