0

Hello i am asking if there is any other way to pattern match against a type besides case or left-hand-side pattern match.

data T=A Int | B Int |C Int | D Int....//many cases

Method 1

getType::T->Char
getType A _ = 'a'
getType B _ ='b'
...............

Method 2:

getType::T->Char
getType x=case x of 
          A _ -> 'a'
          B _  -> 'b'
          ...........

My example above is just an example for its sake ..i assume there are some easy ways if i just want to associate the "reflected'"name of the data constructor with its lower-case-char.

I am more like curious if there are any other ways / constructs in haskell when you want to achive pattern matching.

chi
  • 111,837
  • 3
  • 133
  • 218
Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152
  • This doesn't look like a duplicate of the indicated question to me. An answer to "can you use constructor wildcards" is not an answer to "are there any other constructs for pattern matching". – Ben Oct 18 '18 at 21:32

1 Answers1

2

Pattern matching is the primary way to do this, and anything else will be defined in terms of the pattern matching approach. In general, the text A won't be around at runtime, so normal code can't treat it like a string.

I can't give specific style recommendations since you've said that the example above is not the actual code you are working on. Personally, I have lots of simple functions like getType. It's only when I have hundreds of lines like that, or on types that change often, that I start looking for other approaches.

Haskell also has a rich collection of features for compile-time code generation. GHC Generics and Template Haskell are two powerful & widely-used ways. Both can be used to reduce boilerplate. For example, the aeson library can generate toJSON and fromJSON functions using the names of the data constructors and fields. (It actually provides two implementations, one with GHC Generics, and one with Template Haskell.) In either case, the generated code will use pattern matching, just like your example above.

bergey
  • 3,041
  • 11
  • 17