[Haskell-beginners] type classes and multiple implementations

Chaddaï Fouché chaddai.fouche at gmail.com
Sat Jun 6 12:00:50 EDT 2009


On Fri, Jun 5, 2009 at 7:09 PM, Sean Bartell<wingedtachikoma at gmail.com> wrote:
>    by_type :: Storage a => String -> String -> IO a
> This function must, for any Storage type, take any two strings and produce
> an IO value of that type. (by_type "disk" "xyz" :: Memory must be valid.) It
> doesn't really have the option of choosing which instance of Storage to use.
>
> In pure Haskell, you would probably have to do something like
>   type Storage = Disk Handle | Memory String
>   by_type :: String -> String -> Storage
> That way, by_type can return any Storage it wants.
>
> I'm sure there are also ways to do what you want with extensions.

I think the point is to be able to extend the storage methods in
another module ? If not, Sean's solution is what you want.
If you want to use the type class to allow anyone to add a new method
in his own module, you can use existential type, like :

> data Store = forall a . Storage a => Store a

and then your byType :
> byType "disk" x = Store (open x :: Disk)
> byType "memory" x = Store (open x :: Memory)

See XMonad and its Layout type for an example of this method.

-- 
Jedaï


More information about the Beginners mailing list