Reputation: 13908
I have a data structure like so:
data MyType = Either Bool Int
Now I have a function like so:
myFunc :: MyType -> Int
myFunc mt = Right mt
My goal is to get the Int
value out of the myType
but when I try to compile this function I get the following error:
Couldn't match expected type `Int'
with actual type `Either a0 MyType'
In the expression: Right mt
In an equation for `myFunc': myFunc mt = Right mt
What am I doing wrong?
Upvotes: 0
Views: 585
Reputation: 52290
first note that you data
definition is of as Cactus and Daniel mentioned - for now I assume you wanted
type MyType = Either Bool Int
if you really wanted data MyType = Either Bool Int
then the situation is the same as I describe bellow with data MyType = MyType ...
as an Either Bool Int
can have either a Bool
value (for example Left True
) or an Int
value (for example Right 42
) your choice is basically to either write a partial function:
myFunc :: MyType -> Int
myFunc (Right number) = number
myFunc (Left _) = error "oho ... there is no number"
or you write a total-one with a default value for the bool case:
myFunc :: MyType -> Int
myFunc (Right number) = number
myFunc (Left True) = 1
myFunc (Left False) = 2
or you change the result type to reflect the incapability of getting some number out (using Maybe
):
myFunc :: MyType -> Maybe Int
myFunc (Right number) = Just number
myFunc (Left _) = Nothing
of course maybe you did want to have a type with both an Bool
and an Int
part - in this case change your type into:
data MyType = MyType Bool Int
and write
myFunc :: MyType -> Int
myFunc (MyType _ nr) = nr
Upvotes: 3
Reputation: 27636
data MyType = Either Bool Int
This does not mean what you think it does. This creates a new algebraic data type called MyType
, with a single constructor called Either
that takes a Bool
and an Int
. So you'll have e.g.
Either True 42 :: MyType
What you want is the ability to refer to the existing type Either Bool Int
using a new name MyType
, i.e. a type synonym. You can define type synonyms using type
instead of data
, i.e.
type MyType = Either Bool Int
this will yield
Left True :: MyType
and
Right 42 :: MyType
Upvotes: 0