[mercury-users] Type inheritance?
David Glen JEFFERY
dgj at cs.mu.oz.au
Tue Sep 23 13:47:36 AEST 1997
> I see the line in the file WORK_IN_PROGRESS:
> * Support for Haskell-style type classes
>
> Could you give a brief description of type classes or references?
Sure. I'll give you a quick description, and a few references to look up if
you want to know more. If that doesn't satisfy you, there's quite a lot in the
literature about type classes that you shouldn't have too much trouble digging
up.
Type classes were added to Haskell in order to provide a uniform way of
expressing ad-hoc polymorphism. In OO terms they allow the programmer to use
interface inheritance. Basically, type classes extend Hindley-Milner style
polymorphism with the ability to constrain type variables to belong to a
particular set of types.
The user is able to declare a "type class", which is an interface that a type
must conform to in order to be part of the class. Here's an example using
Mercury's new type class syntax:
:- typeclass number(T) where [
:- func +(T::in, T::in) = (T::out) is det,
:- func -(T::in, T::in) = (T::out) is det,
:- func *(T::in, T::in) = (T::out) is det,
:- func /(T::in, T::in) = (T::out) is det
].
This says that, in order for a type `T' to be a member of the type class
"number", it must have the +, -, * and / operations divided on it.
We can now declare which type are members (or "instances") of the type class:
:- instance number(int) where [
func(+/2) is integer_addition,
func(-/2) is integer_subtraction,
func(*/2) is integer_multiplication,
func(//2) is integer_division
].
:- instance number(float) where [
func(+/2) is float_addition,
func(-/2) is float_subtraction,
func(*/2) is float_multiplication,
func(//2) is float_division
].
We now have two instances of the number class. We could use this face to write
a predicate which adds a list of "numbers", regardless of whether they are ints
or floats:
:- pred add_list(list(T)::in, T::in, T::out) <= number(T) is det.
^^^^^^^^^^^^
a typeclass constraint
add_list([], Accumulator, Accumulator).
add_list([N|Ns] Accumulator0, Accumulator) :-
add_list(Ns, Accumulator0 + N, Accumulator).
^
just use "+"
This is just a basic example. For more information, look at:
[1] A Gentle Introduction to Haskell, Paul Hudak and Joseph H. Fasel,
Sigplan Notices 27(5), T-1 - T-53, 1992.
[2] Type Classes in Haskell, Coredelia Hall, Kevin Hammond, Simon Peyton Jones
and Philip Wadler, Proc. 5th European Symposium on Programming, pp 241-256,
1994. Springer LNCS 788.
[3] Any textbook about Haskell
If you want to know more, feel free to ask.
dgj
--
David Jeffery (dgj at cs.mu.oz.au) | Kids, you tried your best and
MEngSc student, | you failed miserably. The lesson
Department of Computer Science | is, never try.
University of Melbourne, Australia | -- Homer Simpson
More information about the users
mailing list