[Haskell-beginners] Mixing pattern matching and guards

martin martin.drautzburg at web.de
Tue Dec 22 05:29:32 UTC 2015


Hello all,

I recently wrote this piece of code

import qualified Data.Set as S
[...]
purge :: (Eq cp, Eq ip) => Product cp ip -> Product cp ip
purge (Punion ps)
        | ps' == S.empty = Pempty
        where ps' = S.filter (/= Pempty) ps
purge x = x


and I thought I had missed the "otherwise" case in the guard and I was prepared to see a "non exhaustive ..." error, but
to my amazement it works

*Main> purge $ Punion $ S.fromList [Packed 1 Pempty]
Punion (fromList [Packed 1 Pempty])


As this is a Punion, it should match the first pattern, but not the guard. It seems to fall right through to the second
pattern. Is this the way it works?


More information about the Beginners mailing list