Sorry I don’t think I was perfectly clear, let me try one more time. What I meant by saying the issue wasn’t really about otherwise
is that you could have written a function that didn’t have all cases accounted for and it still would have been accepted (you don’t want to do that, but you could). For example
bar a b
| a < b = 1
| b < a = 2
This will run. But what happens when you call bar 3 3
? It will give a runtime error of "Non-exhaustive patterns in function bar"
because you have some patterns that aren’t covered. The function will still run, though. So its not that your error was about needing to use otherwise
to have all of the cases covered, it was purely about the syntax, the fact that you didn’t have an assignment statement after the test.
As wyager said, you can think of otherwise
as just an alias for True
. Haskell checks all of the patterns in order from top to bottom, seeing if the first is True
, and if not moving on to the second and so on. Since otherwise
will always be True
, if it gets to that point the function will always return that case. This is a totally fine thing to do, it is useful and helps cover all cases when it is appropriate. It is true that your rewrite of the function today covers all cases without needing otherwise
and that is great! I just want to clarify what I said and stress the point that your issue conceptually had nothing to do with otherwise
itself, it had to do with you writing something like
foo x
| bar = baz
| qus
which is a syntax error because you need an assignment statement for each guard.
You don’t need to use otherwise
, although you definitely can, and you don’t need cover all cases, although you absolutely should. You just need to have the correct syntax or else it won’t work.