Edit: see this reply
Elm has built-in typeclasses like number
and comparable
(maybe they aren’t actually called typeclasses). For example, number
means that the value can either be Int
or Float
.
I don’t think there is currently any need to be able to define custom typeclasses, but the ability to extend the built-in ones would be very useful.
Typeclasses in Elm basically define what operators are supported by a type. For example, the number
typeclass includes all types that support +
, -
, and other arithmetic operators. Extending these typeclasses allows us to make custom types work with the built-in operators.
What this means is that typeclasses could be extended by simply defining the functions that implement these operators. For example, here is a type that represents a fraction:
module Fraction exposing (..)
type alias Fraction =
{ numerator : Int
, denominator : Int
}
Currently, there is no way to make it possible to do fraction1 + fraction2
; we have to do Fraction.add fraction1 fraction2
(Fraction
is a module). This is very verbose. Another problem is that we can’t pass a Fraction
as an argument to functions like List.sum
.
Like I said earlier, Elm typeclasses define what operators a type supports. I think it should be possible for a custom type to extend a typeclass simply by defining a function for all of the necessary operators. It would be done with something like this:
-- Fraction refers to a type
Fraction.compare : Fraction -> Fraction -> Order
Fraction.compare a b =
-- ...
Defining the function shown above would automatically make Fraction
a comparable
type. So now we can do things like fraction1 < fraction2
. More importantly, we can do min fraction1 fraction2
without having to redefine min
.
There should also be a syntax for explicitly saying that a type is part of a typeclass. It needs to work well with types that use type variables. Maybe something like this:
type alias Fraction [ comparable, number ] =
-- ...
What do you think of this idea?