I ran across a piece of code recently that used Haskell's otherwise
to pattern match on a list. This struck me as odd, since:
ghci> :t otherwise
otherwise :: Bool
So, I tried the following:
ghci> case [] of otherwise -> "!?"
"!?"
I also tried it with various other patterns of different types and with -XNoImplicitPrelude
turned on (to remove otherwise
from scope), and it still works. Is this supposed to happen? Where is this documented?
It's not equivalent to _
, it's equivalent to any other identifier. That is if an identifier is used as a pattern in Haskell, the pattern always matches and the matched value is bound to that identifier (unlike _
where it also always matches, but the matched value is discarded).
Just to be clear: the identifier otherwise
is not special here. The code could just as well have been x -> "!?"
. Also, since the binding is never actually used, it would make more sense to use _
to avoid an "unused identifier" warning and to make it obvious to the reader that the value does not matter.
Just since nobody has said it yet, otherwise is supposed to be used as a guard expression, not a pattern. case ... of pat | ... -> ... | otherwise -> ... Now its definition as True is important. – Reid Barton
An example:
fact n acc
| n == 0 = acc
| otherwise = fact (n-1) $! (acc * n)
Since otherwise
is True
, that second guard will always succeed.
Note that using otherwise
in a pattern (as opposed to a guard) is likely to confuse people. It will also trip a name shadowing warning if GHC is run with the appropriate warnings enabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With