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?
Also, we can use any number of or operators there is no such restriction for that. Or operator is represented by using the '||' double pipe symbol in Haskell. Also, it is an in-built operator available in Haskell, we don't require to include anything to use this while programming.
Haskell : case expressions. A case expression must have at least one alternative and each alternative must have at least one body. Each body must have the same type, and the type of the whole expression is that type.
The case expression in Haskell Many imperative languages have Switch case syntax: we take a variable and execute blocks of code for specific values of that variable. We might also include a catch-all block of code in case the variable has some value for which we didn't set up a case.
You do that by putting a name and an @ in front of a pattern. For instance, the pattern xs@(x:y:ys). This pattern will match exactly the same thing as x:y:ys but you can easily get the whole list via xs instead of repeating yourself by typing out x:y:ys in the function body again.
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
.
foo x | x `elem` [A, C, G] = ... | x `elem` [B, D, E] = ... | otherwise = ...
with guards:
factorial n | n < 2 = 1 | otherwise = n * (factorial (n - 1))
with pattern matching:
factorial 0 = 1 factorial 1 = 1 factorial n = n * (factorial (n - 1))
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