This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

Polymorphic Variants
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2007-01-19 (09:39) From: Dirk Thierbach Subject: Re: Fwd: [Caml-list] Polymorphic Variants
```On Thu, Jan 18, 2007 at 09:14:09PM +0000, Jon Harrop wrote:
> On Thursday 18 January 2007 16:23, Tom wrote:

>> No... i rather thought it that way:
>>      x is anything
>>      x * x is either int or float, so x is either int or float
>>      x * x + x * x is either int or float, so the two (x * x) are either
>> both int or both float
>>      sqrt accepts a float argument, so x * x + x * x must be float, so (x *
>> x) must be float, so x must be float.

BTW, that's what Haskell's type classes do:

Prelude> :t \x -> x
\x -> x :: forall t. t -> t

Prelude> :t \x -> x * x
\x -> x * x :: forall a. (Num a) => a -> a
Prelude> :t \x -> (x * x) + (x * x)
\x -> (x * x) + (x * x) :: forall a. (Num a) => a -> a

Prelude> :t \x -> sqrt x
\x -> sqrt x :: forall a. (Floating a) => a -> a

In the first case, x can have any type. In the next two, it must be
a number (int, float, etc.). In the last case, it must be a specific kind
of number, namely "float-like", which includes (single precision) Float,
Double, and Complex.

> Much better. Except I want + to work on int, float, float32, 'a^n
> (static vectors), 'a^n^m (static matrices), 'a array, 'a list, 'a
> set. Not only that, I want + and * to work on two values of
> different types: date+time, float*vector and so on.

Sure. Just write the apropriate instances for the type class, if
it isn't defined already. Encoding dimensionalities into types
can require a bit of magic :-)

> Hell, I want to overload 0 to mean 0, 0., 0. + 0.i, zero vector and
> the zero matrix.

No problem either: Number literals like "0" are translated into the
type class, you can generate the apropriate constant.

> Of course, the zero matrix has arbitrary dimensionalities that could
> be static, so my type now contains variables for those.

Again, no problem.

Of course, you pay for that flexibility by having to pass around
dictionaries at runtime (unless you specialize early, or the compiler
is really clever about inlining and specializing).

> You see how things will get more complicated to define correctly, slower to
> compile and much harder to comprehend when things go wrong?

Certainly. One has to be very careful what to allow and what to disallow.
But at least those very basic examples work fine.

- Dirk

```