Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can resolve the warning in this special case by doing this:</p> <pre><code>gb_groupBy p input = foldr step [] input where step item acc = case acc of [] -&gt; [[item]] (xs:xss) -&gt; if p (head xs) item then (item:xs):xss else [item]:acc </code></pre> <p>The pattern matching is then complete, and the "impossible" condition of an empty list at the head of the accumulator would cause a runtime error but no warning.</p> <p>Another way of looking at the more general problem of incomplete pattern matchings is to see them as a "code smell", i.e. an indication that we're trying to solve a problem in a suboptimal, or non-Haskellish, way, and try to rewrite our functions.</p> <p>Implementing groupBy with a foldr makes it impossible to apply it to an infinite list, which is a design goal that the Haskell List functions try to achieve wherever semantically reasonable. Consider</p> <pre><code>take 5 $ groupBy (==) someFunctionDerivingAnInfiniteList </code></pre> <p>If the first 5 groups w.r.t. equality are finite, lazy evaluation will terminate. This is something you can't do in a strictly evaluated language. Even if you don't work with infinite lists, writing functions like this will yield better performance on long lists, or avoid the stack overflow that occurs when evaluating expressions like</p> <pre><code>take 5 $ gb_groupBy (==) [1..1000000] </code></pre> <p>In <a href="http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/libraries/base/Data/List.hs?rev=1.26" rel="noreferrer">List.hs</a>, groupBy is implemented like this:</p> <pre><code>groupBy :: (a -&gt; a -&gt; Bool) -&gt; [a] -&gt; [[a]] groupBy _ [] = [] groupBy eq (x:xs) = (x:ys) : groupBy eq zs where (ys,zs) = span (eq x) xs </code></pre> <p>This enables the interpreter/compiler to evaluate only the parts of the computation necessary for the result. <a href="http://undergraduate.csse.uwa.edu.au/units/CITS3211/lectureNotes/tourofprelude.html#span" rel="noreferrer">span</a> yields a pair of lists, where the first consists of (consecutive) elements from the head of the list all satisfying a predicate, and the second is the rest of the list. It's also implemented to work on infinite lists.</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