Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching, matching multiple character

If I have a function that takes a string and say returns an int, I can match the first character of the string, using pattern matching:

f :: String -> Int
f ('A' : _) = 1
f ('B' : _) = 0
f ('C' : _) = 1
f _ = 2

is there a way to match A or C in one? Something like:

f :: String -> Int
f ('A'||'C' : _) = 1
f ('B' : _) = 0
f _ = 2

or even this (which would be useful if there is some calculation rather than just returning a constant_)

f :: String -> Int
f ('A' : _)
f ('C' : _) = 1
f ('B' : _) = 0
f _ = 2
like image 653
Jonathan. Avatar asked Dec 15 '22 04:12

Jonathan.


1 Answers

Haskell does not have alternation in the pattern matching. You could solve the problem using recursion:

f :: String -> Int
f ('A' : rest) = f ('C' : rest)
f ('B' : _) = 0
f ('C' : _) = 1
f _ = 2

You might consider using guards:

f ('B' : _) = 0
f (x : _) | x `elem` "AC" = 1
f _ = 2
like image 152
Joni Avatar answered Dec 29 '22 19:12

Joni