Hacker News new | ask | show | jobs
by jmite 3140 days ago
Rust's traits are basically Haskell typeclasses, with a few extensions enabled, like multiple parameters.

Trait objects are basically existential types, with a few more restrictions on them. But in essence polymorphism in Haskell and Rust are very similar.

The big thing Rust is missing is higher kinded polymorphism, ie the ability to abstract over type constructors. This makes it easy, for example, to abstract over a container type while putting different things in that container.

This has get approved in the Associated Type Constructors RFC, but it's still in the works for actually landing.

1 comments

One thing no-one else has mentioned yet: in Haskell you can’t provide a specialised implementation of a generic function. In Rust you can.

Whilst this is obviously useful, it makes it impossible to perform parametricity type-based reasonbig.

Of course you can. The good old {-# LANGUAGE OverlappingInstances #-}.
In Haskell you have to supply the entire instance, versus just specializing one method as you can do in Rust. Also in Haskell this extension is not recommended for general use and you won’t often find specialization like this in the wild.
The typical way to do multiple instances for a given type is with trivial newtype wrappers for each instance. See the "Sum" and "Product" monoid instances (although these wrappers are also necessary for instance decidability). This is fine "in the wild."

Also, I'm not sure why you would ever want a "partial instance," as it would mean that your program could be unsafe but still typecheck (I haven't checked out Rust's implementation or motivation). Just use more specific classes, and you can even use a "generic" "instances of the components imply an instance of the whole" class and instance.

When you specialize an instance in Rust, by definition it already has a valid instance that covers that type. So implementing a single method is fine - the other ones are provided by the instance you are specializing.

Newtypes also exist in Rust but this is an alternative that is not the same as the overlapping instances extension.

Rust will find out why as soon as this gets widespread.

You can either have overloading classes or you can have your classes declaration independent of the type declarations. You can not have both.

I think you can using GHC Pragmas.