[Haskell-beginners] How do I do inheritance in haskell?

Daniel Trstenjak daniel.trstenjak at gmail.com
Thu May 8 14:21:48 UTC 2014


Hi Dimitri,

> It is not clear to me which one of these should be used and, most importantly,
> which criteria should be used to choose between them.

One criteria should be what you want to achieve, how you want
to operate with your data.


> 1)
> newtype Volume = Volume Double deriving (Show)
> newtype Price  = Price  Double deriving (Show)
> 
> data Order = Bid {price::Price, volume::Volume}
>            | Ask {price::Price, volume::Volume}
>            deriving (Show)
> 
> data OrderBook = OrderBook{ bids::[Order] , asks::[Order] } deriving (Show)

This represenation of an Order gives you the ability to put Bids and
Asks e.g. into the same list, but if you always want to keep them
separate, then there's no point to have an ADT in the first place.


> 2)
> newtype Volume = Volume Double deriving (Show)
> newtype Price  = Price  Double deriving (Show)
> 
> data Order = Order {price::Price, volume::Volume} deriving (Show)
> 
> newtype Bid = Bid Order deriving Show
> newtype Ask = Ask Order deriving Show
> 
> data OrderBook = OrderBook{ bids::[Bid] , asks::[Ask] } deriving (Show)

If you want to keep Bids and Asks always separate, then this
represenation seems to be more fitting.


> 3)
> newtype Volume = Volume Double deriving (Show)
> newtype Price  = Price  Double deriving (Show)
> 
> class Order a where
>     makeOrder :: String -> String -> a
> 
> data Ask = Ask {aprice::Price, avolume::Volume} deriving (Show)
> instance Order Ask where
>     makeOrder = makeAsk
> 
> data Bid = Bid {bprice::Price, bvolume::Volume} deriving (Show)
> instance Order Bid where
>     makeOrder = makeBid
> 
> data OrderBook = OrderBook{ bids::[Bid] , asks::[Ask] } deriving (Show)

I might prefer the Asks and Bids data types of 2), because factoring out
the common parts might have future benefits, by being able to reuse
functionality on the common parts.

The type class here fulfills something completely different to the
previous two examples and is about the creation of your Asks and Bids.

I don't think that you really need this type class, but you could just
use makeAsk and makeBid without losing anything, because as long as your
types in OrderBook are fixed you gain nothing.


Greetings,
Daniel


More information about the Beginners mailing list