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
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
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