Reputation: 879
Is there a way I can create a function with multiple definitions for different patterns including one that is executed when no of the other function's statements patterns are matched?
E.g.:
someFunc (pattern1) = def1
someFunc (pattern2) = def2
someFunc (<otherwise/all other possible values>) = def3
Or if this is not possible, how can it be achieved?
Thanks in advance!
Best regards, Skyfe.
Upvotes: 0
Views: 547
Reputation: 54058
You can use the wildcard match _
:
isJust :: Maybe a -> Bool
-- Here we don't care about what's inside the `Just`
isJust (Just _) = True
-- Here we don't care what it is, it's not a `Just` so return `False`
isJust _ = False
For clarification, patterns are tried in the order you define them, so the above function is not equivalent to
isJust _ = False
isJust (Just _) = True
because the _
pattern is matched first. What the compiler is actually doing is turning this into a case statement internally, so the first function would be equivalent to
isJust x = case x of
Just _ -> True
_ -> False
and as we know from every other programming language that has ever existed, case statements are tried in order.
Upvotes: 6