[Haskell-cafe] Idiomatic ways to make all instances of a certain class also instances of another?

Alexander Solla alex.solla at gmail.com
Wed Jul 27 00:14:10 CEST 2011


On Tue, Jul 26, 2011 at 1:52 PM, Tim Cowlishaw <tim at timcowlishaw.co.uk>wrote:

> On Tue, Jul 26, 2011 at 7:46 PM, Evan Laforge <qdunkan at gmail.com> wrote:
>
> > Could you give a specific example of the problem you're trying to solve?
>
> Sorry, yes, that'd be useful :-)
>
> So, the project I'm working on involves developing a simulation of a
> securities market. I have a type which models an order book, on which
> orders can be placed or removed (and later filled):
>
> eg.
>
> placeOrder :: (Order e) -> e -> OrderBook -> OrderBook
> deleteOrder :: (Order e) -> e -> OrderBook -> OrderBook
>
> Now, i've chosen to model orders as a typeclass, as there are various
> semantic differences between different types of order that I can model
> as different types implementing this typeclass (limit orders vs market
> orders, buy side vs sell side), and these differences can be specified
> in the type's implementation of the class.


Use Maybe to demarcate nonsense semantics/undefinedness.


> However, there are a number
> of other typeclasses that all orders should also be instances of (and
> in terms of which their semantics don't differ, eg Eq or Ord.
>

data OrderType = Market Size | Limit LimitPrice Expiration Size | Stop
(Either Percent Price)

newtype Sell = Sell OrderType
newtype Buy = Buy OrderType

newtype Order = Order (Either Buy Sell)


 class Order o where
>  price :: o -> Int
>  size :: o -> Int
>
>
size :: Order -> Int
size (Order (Left (Buy (Market s))) = s
size (Order (Left (Buy (Limit _ _ s))) = s
etc.


> I'd like to be able to specify an Eq instance for all types of class
> Order in a manner similar to this:
>
> instance (Order o) => Eq o where
>  o1 == o2 = (price o1 == price o2) && (size o1 == size o2)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110726/8a62ba83/attachment.htm>


More information about the Haskell-Cafe mailing list