Haskell `otherwise` is synonymous with` _`?

I recently looked at a code snippet that Haskell otherwise to match patterns in a list. This seemed strange to me because:

 ghci> :t otherwise otherwise :: Bool 

So, I tried the following:

 ghci> case [] of otherwise -> "!?" "!?" 

I also tried it with various other templates of different types and included -XNoImplicitPrelude (to remove otherwise from the scope) and it still works. Is this supposed to happen? Where is this documented?

+8
haskell
source share
2 answers

It is not equivalent to _ , it is equivalent to any other identifier. That is, if an identifier is used as a template in Haskell, the template always matches and the agreed value is bound to that identifier (unlike _ , where it also always matches, but the matching value is discarded).

Just to be clear: otherwise identifier is not special here. The code could also be x -> "!?" . In addition, since the binding is never used, it would be wise to use _ to avoid the โ€œunused identifierโ€ warning and make it clear to the reader that the value does not matter.

+16
source share

Since no one has said this yet, otherwise it is assumed that it is used as a protective expression, not a template. case ... of pat | ... โ†’ ... | otherwise โ†’ ... Now defining it as True is important. - Raid Barton

Example:

 fact n acc | n == 0 = acc | otherwise = fact (n-1) $! (acc * n) 

Since otherwise is True , the second defender will always be successful.

Please note that using otherwise in the template (unlike a guard) can confuse people. It will also disable the name hiding warning if the GHC is started with the corresponding warnings turned on.

+9
source share

All Articles