[Haskell-cafe] class-instance

Ketil Malde ketil at malde.org
Mon Jan 17 15:29:33 CET 2011


Patrick Browne <patrick.browne at dit.ie> writes:

> I think the problem is there is just one constant p1 in the class and
> there needs to be multiple constants in the implementation (one for each
> person). It seems difficult to specify this using type classes So, some
> data declaration as you suggest will probably be needed.

Yes.  I'm going to assume you're a beginner here (always a dangerous
assumption on this list, no offense if I just misinterpret what you're
trying to do).  The (one?) difference between a Haskell class and a typical OO
class, is that an instance of a class in Haskell is a *type*, but an
instance of a class in, say, C++, is an object (which we like to call a
*value*, to dissociate ourselves from That Other Crowd :-).

Let's ignore the 'name' for now.

  class Person p where
     id :: p

means that a *type* p is in the Person class if you can identify a value
of type p that is the person-id for that type.  So Int is a person-type
if you say 

  instance Person Int where
     id = 42

and (id::Int) will return 42 in subsequent code.  Similarly, you can
make other Person-types by instantiating them and defining id¹ for them.

A function can take a Person-type as a parameter, for instance

  foo :: Person p => p -> Bool
  foo x = bla blah (id x) blah

Alternatively, 

  data Person = P Int

on the other hand declares a new type called "Person", with a data
constructor (tag) P, and containing just an Int.  This means you can
make multiple values of this type, so 

  P 4, P 42, and P 911 

are all Persons your program can juggle around in your program.  A
function can take these persons:

  foo :: Person -> Int -> Bool
  foo (P x) y = bla bla apply int functions on x and y

Hope that was helpful?

-k

¹ Dumb name, as this is the identity function.  Sorry.
-- 
If I haven't seen further, it is by standing in the footprints of giants



More information about the Haskell-Cafe mailing list