[Haskell-cafe] class-instance

Ketil Malde ketil at malde.org
Mon Jan 17 14:04:56 CET 2011


Henning Thielemann <lemming at henning-thielemann.de> writes:

>> class PERSON a b where
>>  p1 :: a
>>  name :: a -> b

A multi-parameter typeclass is a relation over types...

>> instance PERSON  Int String where
>>  p1 = 1
>>  name p1 = "john"
         ^--note that this is just an unused paramter,
          it is clearer to specify 'name _ = "john"'

...so this instance gives the PERSON relation for Int and String.

So other PERSONs would have different types, say:

  instance PERSON Double Int where
     p1 = 3.14
     name = 200

Does that make sense?  It looks a bit strange to me.

> The problem is certainly, that a Haskell interpreter has no way to
> infer types, thus you have to annotate type of both argument and
> result of 'name', and type annotation for 'p1' is not possible at all,
> because 'b' does not occur in its type. You have to write
>
> name (12::Int) :: String

And (correct me if I'm wrong) there's no way to do that for p1, since
there is no way to specify which type 'b' you want.  You could have

  instance PERSON Int String where
    p1 = 1
    name = "john"

and

  instance PERSON Int Double where
    p1 = 24
    name = 3.14

then the system would have no way to figure out which value you want
even if you specify (p1::Int).

Are you sure you didn't want:

  data Person = P Int String

?

-k
-- 
If I haven't seen further, it is by standing in the footprints of giants



More information about the Haskell-Cafe mailing list