Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell syntax for 'or' in case expressions

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?

like image 996
Rahul Göma Phuloré Avatar asked Sep 29 '11 21:09

Rahul Göma Phuloré


People also ask

How do you write or in Haskell?

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.

How do you write a case statement in Haskell?

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.

What is case Haskell?

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.

How do you do pattern matching in Haskell?

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.


2 Answers

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          = ... 
like image 125
hammar Avatar answered Oct 08 '22 10:10

hammar


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)) 
like image 22
Simon Bergot Avatar answered Oct 08 '22 09:10

Simon Bergot