Using symbolic values in the case expression

Hi, I'd like to do something like this - Instead of doing this - f x = case x of 1 -> "One" 2 -> "Two" I'd like to do this - v1 = 1 v2 = 2 f x = case of v1 -> "One" v2 -> "Two" Is that possible? -- Regards, Kashyap

On 11 Nov 2010, at 17:03, C K Kashyap wrote:
Hi, I'd like to do something like this -
Instead of doing this -
f x = case x of 1 -> "One" 2 -> "Two"
I'd like to do this -
v1 = 1 v2 = 2
f x = case of v1 -> "One" v2 -> "Two"
Is that possible?
Pattern matching against expressions is not possible, except in the very very limited case of n + k patterns, so no. Bob

On Thursday 11 November 2010 18:03:10, C K Kashyap wrote:
Hi, I'd like to do something like this -
Instead of doing this -
f x = case x of 1 -> "One" 2 -> "Two"
I'd like to do this -
v1 = 1 v2 = 2
f x = case of v1 -> "One" v2 -> "Two"
Is that possible?
No, case does a pattern match, it checks whether the expression matches the pattern (patterns are defined in the report, section 3.17, http://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-580003.17), so variable names (identifiers beginning with a lower case letter) match everything.

Is there a way out? What I need to do is implement a protocol - so it would be nice to write a case expression with patters being symbolic. -- Regards, Kashyap

On Thursday 11 November 2010 18:45:43, C K Kashyap wrote:
Is there a way out? What I need to do is implement a protocol - so it would be nice to write a case expression with patters being symbolic.
Guards? case expr of res | res == v1 -> "One" | res == v2 -> "Two" _ -> error "Three" Or perhaps a little preprocessor abuse might help. {-# LANGUAGE CPP #-} #define V1 1 #define V2 2 case expr of V1 -> "One" V2 -> "Two" _ -> error "Three"

On 11 November 2010 17:03, C K Kashyap
v1 = 1 v2 = 2
f x = case x of v1 -> "One" v2 -> "Two"
The closest I can thin is the following: f x | x == v1 = "One" | x == v2 = "Two" But, keep in mind, this is *not* the same thing. It requires Eq on x, and you lose all the exhaustiveness/overlapping checks pattern matching provides. HTH, -- Ozgur Akgun
participants (4)
-
C K Kashyap
-
Daniel Fischer
-
Ozgur Akgun
-
Thomas Davie