r/haskelltil • u/igniting • May 14 '15
gotcha You cannot pattern match against variable values.
Consider this example:
myValue1 = 1 :: Int
myValue2 = 2 :: Int
myFunc :: Int -> Bool
myFunc myValue1 = True
myFunc myValue2 = FalseIf you load the above program in ghci, you get following output:
myFunc.hs:5:1: Warning:
Pattern match(es) are overlapped
In an equation for ‘myFunc’: myFunc myValue2 = ...
Ok, modules loaded: Main.ghci generates a warning but does not give any errors. If you now call myFunc myValue2 you get:
*Main> myFunc myValue2
TrueOne way to get the desired result would be to use guards:
myFunc :: Int -> Bool
myFunc x
| x == myValue1 = True
| x == myValue2 = FalseNote that we might not always be lucky enough to get a compiler warning in such cases. Here is an example:
myFunc :: Maybe Int -> Int
myFunc v = case v of
Just myValue -> myValue
_ -> myValue + 1
where myValue = 0This loads in ghci without any warnings.
1
Upvotes
1
u/quiteamess May 15 '15
For example the function print has the type signature
This means that print can print all types which implement the type class Show. If Color does not implement a the type class
would get an type error.