I want pass a sub data type into function.
An example:
data Car a = Ford | Opel | BMW | Mercedes a deriving (Show)
data Mercedes a = SClass a| CClass a| MClass a
myfunc::Car->String
myfunc a = show a ++ " works correctly"
but I do:
myfunc CClass “x”
it says
not in scope: constructor CClass
To achieve “sub”-types, one has a few options. The first is just to use more
datatypes, as you are attempting:Note that being a type constructor is different to being a data constructor, so one can’t just use
data Car = .. | Mercedes a: this is saying that one of the ways to make aCar Stringis just by sayingMercedes "a", it has no correlation with the type calledMercedes. Now one can just use a function like:And your example would be:
Another way to allow “subtyping” like this is to use a type class (depending on the specifics, this might be a better option). E.g.
Your example of
myfuncmight be:Also note that one must call functions like
function (Ford (Ford "a"))(orfunction (CClass "a")) with parenthesis.