[Haskell-beginners] pattern matching on a common element
Daniel Trstenjak
daniel.trstenjak at gmail.com
Fri Nov 25 09:19:14 UTC 2016
Hi Rahul,
On Fri, Nov 25, 2016 at 12:06:06PM +0530, Rahul Muttineni wrote:
> data X =
> A1 { name :: String, d :: Double}
> | A2 { name :: String, i :: Int}
> | A3 { name :: String, d1 :: Double, i1 :: Int}
>
> Now you can use `name` directly to get the string component of the different
> variants.
It's not recommended to mix record syntax and ADTs, because you
can get runtime errors that the compiler can't catch during compile
time, like calling:
i (A1 "foo" 3.2)
If you're having the same field in all variants, then an
other approach might be better:
data A = Ai Int | Ad Double | Aid Int Double
data X = X { name :: String, a :: A }
Greetings,
Daniel
More information about the Beginners
mailing list