Well, firstly you have a typo: data constructors must be uppercase:
data Something = Foo Integer
| Bar Bool
What you are asking for is exactly what pattern matching is for. If you have a Something
value called s
:
case s of
Foo f -> ... -- f is of type Integer in this "block"
Bar b -> ... -- b is of type Bool in this "block"
This is how you generally approach this problem, because any kind of getter on this sort of data type will throw an error if it is constructed with the "wrong" constructor, and this allows you to handle that case. You can make a safe getter with something like Maybe
, but a lot of times this will end up involving more boilerplate anyway.