Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell's `otherwise` is a synonym for `_`?

Tags:

haskell

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?

like image 233
YellPika Avatar asked Apr 16 '15 22:04

YellPika


2 Answers

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.

like image 60
sepp2k Avatar answered Sep 22 '22 22:09

sepp2k


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.

like image 9
2 revs Avatar answered Sep 23 '22 22:09

2 revs