Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Think about it: your code is saying "when x is in the remainder, prepend x to the result", i.e. creating a duplicate. You just need to change it to "when x is not in the remainder, prepend x to the result" and you get the correct function.</p> <p>This function differs from <code>Data.List.nub</code> in an important way: this function is more strict. Thus:</p> <pre><code>test [1..] = _|_ -- infinite loop (try it) nub [1..] = [1..] </code></pre> <p><code>nub</code> gives the answer correctly for infinite lists -- this means that it doesn't need the whole list to start computing results, and thus it is a nice player in the stream processing game.</p> <p>The reason it is strict is because <code>elem</code> is strict: it searches the whole list (presuming it doesn't find a match) before it returns a result. You could write that like this:</p> <pre><code>nub :: (Eq a) =&gt; [a] -&gt; [a] nub = go [] where go seen [] = [] go seen (x:xs) | x `elem` seen = go seen xs | otherwise = x : go (x:seen) xs </code></pre> <p>Notice how <code>seen</code> grows like the <em>output so far</em>, whereas yours grows like the <em>remainder of the output</em>. The former is always finite (starting at <code>[]</code> and adding one at a time), whereas the latter may be infinite (eg. <code>[1..]</code>). So this variant can yield elements more lazily.</p> <p>This would be faster (O(n log n) instead of O(n^2)) if you used a <code>Data.Set</code> instead of a list for <code>seen</code>. But it adds an <code>Ord</code> constraint.</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