[Haskell-cafe] Idiomatic ways to make all instances of a certain class also instances of another?
Tim Cowlishaw
tim at timcowlishaw.co.uk
Tue Jul 26 22:52:39 CEST 2011
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. 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.
For instance, for a typeclass representing the interface that any
Order type should implement:
class Order o where
price :: o -> Int
size :: o -> Int
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)
I hope this clarifies my query - I'd be interested to know if this is
possible, and whether or not it's a recommended approach, and if not,
how else I could achieve something similar.
Many thanks,
Tim
More information about the Haskell-Cafe
mailing list