Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell pattern matching - how to use constants variable

Tags:

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?

like image 980
Kevin Avatar asked Sep 16 '10 16:09

Kevin


People also ask

How do you denote pattern matching in Haskell?

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

What is pattern matching in Haskell explain with example?

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.

Can you pattern match in guards Haskell?

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

What is a guard in Haskell?

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.


1 Answers

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.

like image 91
Don Stewart Avatar answered Oct 02 '22 18:10

Don Stewart