In F#, I can use |
to group cases when pattern matching. For example,
let rec factorial n =
match n with
| 0 | 1 -> 1 // like in this line
| _ -> n * factorial (n - 1)
What's the Haskell syntax for the same?
In F#, I can use |
to group cases when pattern matching. For example,
let rec factorial n =
match n with
| 0 | 1 -> 1 // like in this line
| _ -> n * factorial (n - 1)
What's the Haskell syntax for the same?
with guards:
with pattern matching:
There is no way of sharing the same right hand side for different patterns. However, you can usually get around this by using guards instead of patterns, for example with
elem
.Building on some of the above answers, you can (at least now) use guards to do multiple cases on a single line:
So, an input of "Bob", "John", or "Joe" would give you an "ok!", whereas "Frank" would be "not ok!", and everything else would be "bad input!"
Here's a fairly literal translation:
View patterns could also give you a literal translation.
Not saying that these are better than the alternatives. Just pointing them out.
I'm not entirely familiar with F#, but in Haskell, case statements allow you to pattern match, binding variables to parts of an expression.
In the theoretical case that Haskell allowed the same:
It would therefore be problematic to allow multiple bindings
There are rare circumstances where it could work, by using the same binding:
And as in the example you gave, it could work alright if you only match literals and do not bind anything:
However:
As far as I know, Haskell does not have syntax like that. It does have guards, though, as mentioned by others.
Also note:
Using
|
in the case statement serves a different function in Haskell. The statement after the | acts as a guard.So if this sort of syntax were to be introduced into Haskell, it would have to use something other than
|
. I would suggest using,
(to whomever might feel like adding this to the Haskell spec.)This currently produces "parse error on input
,
"