On Tue, Jul 26, 2011 at 1:52 PM, Tim Cowlishaw <tim@timcowlishaw.co.uk> wrote:
On Tue, Jul 26, 2011 at 7:46 PM, Evan Laforge <qdunkan@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)