I would ideally like to write something like this:
myValue1 = 1 :: Int myValue2 = 2 :: Int myFunc :: Int -> Bool myFunc myValue1 = True myFunc myValue2 = False
Calling myFunc myValue2
returns True
- not what I intend. I know why this happens, but is there a way to express this in Haskell without resorting to C-style #define
statements?
f is a pattern which matches anything at all, and binds the f variable to whatever is matched. (x:xs) is a pattern that matches a non-empty list which is formed by something (which gets bound to the x variable) which was cons'd (by the (:) function) onto something else (which gets bound to xs ).
In a functional language, pattern matching involves checking an argument against different forms. A simple example involves recursively defined operations on lists. I will use OCaml to explain pattern matching since it's my functional language of choice, but the concepts are the same in F# and Haskell, AFAIK.
The PatternGuards extension, now officially incorporated into the Haskell 2010 language, expands guards to allow arbitrary pattern matching and condition chaining. The existing syntax for guards then becomes a special case of the new, much more general form. You start a guard in the same way as always, with a | .
A guard is basically a boolean expression. If it evaluates to True, then the corresponding function body is used. If it evaluates to False, checking drops through to the next guard and so on. If we call this function with 24.3, it will first check if that's smaller than or equal to 18.5.
Well, Haskell doesn't unify names like this. Those new 'myValue1' and '2' identifiers are new variables you're binding.
The most Haskelly way is to use strong types and pattern matching:
data Values = D1 | D2 myFunc :: Values -> Bool myFunc D1 = True myFunc D2 = False
Giving you a static guarantee only "1" or "2" can be passed to myFunc, proper symbolic matching and you even retain conversion to integers by deriving Enum.
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