According to What does comparable mean in Elm? comparable
is built-in type constraint that can be used to limit type variables to those built-in types that are, well, comparable. The following questions comes to mind (and are not so easy to find out):
f
that accepts List of elements (of a same but uncertain type) each of which can be used as an argument to some function g
(i.e. f
accepts List a
and moreover inst
being of type a
implies that g(inst)
makes sense)Type variables a and b are used by convention in many places, but some type annotations benefit from more specific names. There is a special variant of type variables in Elm called constrained type variables. The most common example is the number type. The negate function uses it:
As a result, it’s extremely rare to have runtime errors in Elm. At this point you may be wondering where exactly in our code do type and data constructors get used. Type constructors are mainly used either in a type declaration or a type annotation, whereas data constructors are used inside a function body or when we define a top-level constant.
In the How List Works Behind the Scenes section, we learned that List in Elm is defined as a recursive type. At the time, we didn’t know enough about types to fully grasp the idea of recursive types. Now that we know what types are, we’re better positioned to understand what they are. Let’s say we have a list of numbers: [ 16, 5, 31, 9 ].
Note: Custom types are the most important feature in Elm. They have a lot of depth, especially once you get in the habit of trying to model scenarios more precisely. I tried to share some of this depth in Types as Sets and Types as Bits in the appendix.
Besides comparable
(ints, floats, chars, strings, lists, and tuples) there are also appendable
(strings, text, and lists) and number
(ints and floats). I have not seen an authoritative list (outside of the compiler source).
There is no way to define similar typeclasses of your own.
Yes, this limits what functions you can write. No one has convinced Evan that this limit is a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With