Reputation: 83
If you have a data type
data Something = foo Integer
| bar Bool
Is there anyway I define "getters" that unwrap the Something type to get just the Integer or Bool? Right now it would be like (foo Integer) and (bar Bool). I just want the Integer or Boolean values.
Upvotes: 2
Views: 883
Reputation: 10783
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.
Upvotes: 7