[Haskell-cafe] Question about type families

Gábor Lehel illissius at gmail.com
Tue Sep 13 20:25:50 CEST 2011

On Tue, Sep 13, 2011 at 4:58 PM, Grigory Sarnitskiy <sargrigory at ya.ru> wrote:
> Is there a way to make the following code working?
> {-# LANGUAGE TypeFamilies #-}
> data family Foo a
> data instance (Num a)        => Foo a = A a deriving Show
> data instance (Fractional a) => Foo a = B a deriving Show
> I want to have different constructors for 'Foo a' depending on a class of 'a'. Note also, that in the example above I also meant constructor A to be available for (Fractional a) => Foo, since in that case 'a' has Num too. How can I achieve it, maybe not with TypeFamilies?

Thinking further... just guessing, but maybe you want a GADT?

data Foo a where
    FooN :: Num a => a -> Foo a
    FooF :: Fractional a => a -> Foo a

You use FooF for Fractionals, and either one for Nums. 'a' is required
to be an instance of the class, and the instance is made available
when pattern matching on the constructor (unlike with datatype
contexts). But, as I said, automating the choice based on whether 'a'
is or is not an instance of Fractional is impossible.* You have to
specify it explicitly.

* You can probably do it with Template Haskell, but you probably don't want to.

Work is punishment for failing to procrastinate effectively.

More information about the Haskell-Cafe mailing list