[Alice-users] Re: CTM Chapter 4

Andreas Rossberg rossberg at ps.uni-sb.de
Sun May 8 20:07:47 CEST 2005

Chris Rathman <chrisr at virtualcommitment.com>:
> Didn't realize until a few minutes ago that Alice has a
> byNeed function which probably is the way I should have translated some of
> the examples (I just interspersed lazy which I believe has the same
> semantics).

Yes, byneed is simply defined as

  fun byneed f = lazy f ()

> Only other thing that I'm not sure I understand the full implications is
> statement in the Haskell section about how SML and Oz can achieve an
> similar to Haskell classes by using functors.  No code hangs off that
> section, though I figure it might help to know how one can emulate Haskell
> classes within ML.

Type classes are indeed somewhat similar to modules. You can view a type
class as a special form of signature over some type (or several types, if
you consider multi-parameter type classes). An instance of that class
corresponds to a module matching the signature. For example,

  class Eq a where
    (==) :: a -> a -> Bool

  instance Eq Int where
    (==) = primIntEq

roughly maps to

  signature EQ =
    type t
    val == : t * t -> bool

  structure EqInt : EQ =
    type t = int
    val op== = primIntEq

Using a class method is something like accessing a specific module with a
known signature without mentioning it explicitly - type inference figures
out which module is meant.

  (==) 3 4

would mean

  EqInt.== (3, 4)

Functors come into play when you have instances that are restricted by a
context, e.g.

  instance Eq a => Eq [a] where
    [] == [] = True
    (x:xs) == (y:ys) = x == y && xs == ys
    _ == _ = False

This is related to a functor

  functor EqList (EqA : EQ) : EQ =
    type t = EqA.t list
    fun [] == [] = true
      | (x::xs) == (y::ys) = EqA.== (x, y) andalso xs == ys
      | _ == _ = false

But again, instead of requiring the programmer to explicitly apply the
functor, type inference figures out which instances are needed.

So in a first approximation, you can see type classes as a simple module
mechanism plus some fancy type inference magic that makes its use more
convenient. This convenience can be so significant that it provides a whole
new level of expressive power, especially since type classes cooperate much
better with polymorphism than ML modules do. On the other hand, modules are
a much more general mechanism with wider scope, and type classes do not
address issues like type abstraction and programming-in-the-large.

Merging both concepts is still largely an open issue, raising more difficult
questions than one might think at first.

Hope this helps,

  - Andreas

More information about the alice-users mailing list