[Haskell-cafe] How to specialize a type
Ruben Astudillo
ruben.astud at gmail.com
Sat Oct 17 06:08:44 UTC 2015
Hi. You stack-overflow had good answers, I don't think I will shed new
light on this. But still I will give it a try.
On 16/10/15 04:32, martin wrote:
> Hello all,
>
> Suppose I have a type "Process" which stands either for a Train or a
> moving Belt. In both cases there is a place of departure and a place of
> arrival. However the other parameters which describe a Process differ.
> A Train has departure and arrival times, but a Belt has a speed.
>
> I tried the following:
>
>
> type PlaceDep = Int
> type PlaceArr = Int
>
> data Process = Train PlaceDep PlaceArr TP
> | MovingBelt PlaceDep PlaceArr BP deriving (Eq, Show)
>
> data TP = TP Int deriving (Eq, Show)
> data BP = BP Int deriving (Eq, Show)
You could use a newtype here. This is the intended use case of them as
you want a semantically different type but an underlying same
representation (and possible some instances of such representation).
Something like this
newtype TP = TP Int deriving (Eq, Show)
newtype BP = BP Int deriving (Eq, Show)
> prc1 = Train 10 11 (TP 1)
> prc2 = MovingBelt 12 13 (BP 2)
>
>
> What I don't like about this is that the fact that all Processes have
> PlaceDep and PlaceArr appears somewhat "coincidental".
>
> This in contrast, captures the common parts more clearly:
>
> type PlaceDep = Int
> type PlaceArr = Int
>
> data ProcessParams = DepartureTime Int | Speed Int
> deriving (Eq, Show)
>
> data Process = Process PlaceDep PlaceArr ProcessParams
> deriving (Eq, Show)
>
> prc1 = Process 10 11 (DepartureTime 1)
> prc2 = Process 12 13 (Speed 2)
This just seems a trade-off if you want to know with what are you dealing
just matching the outer constructor or more of the problem won't care
about it. Not really a dichotomy worth caring about much anyways
> Is this the classic way of specializing a type or are there better options
I would just stick to sum types (the first approach) but I don't know the
whole context of the problem. BTW "specializing a type" has a concrete
meaning in haskell. It grabs a polymorphic function and gives it a more
concrete type. An usual example is
id :: a -> a
id x = x
id2 :: Char -> Char
id2 c = id c
which hopefully is clear on what I am going about
More information about the Haskell-Cafe
mailing list