Elm docs give no example usage, so it's hard to understand what the type specs mean. In several places I've seen "a" used as an argument identifier, like in Platform.Cmd:
map : (a -> msg) -> Cmd a -> Cmd msg
What does this mean? How would I use Cmd.map
?
Here is part of Elm Guide about reading Types Annotations:
> [ "Alice", "Bob" ]
[ "Alice", "Bob" ] : List String
> [ 1.0, 8.6, 42.1 ]
[ 1.0, 8.6, 42.1 ] : List Float
> []
[] : List a
In the first case, we have a List filled with String values. In the second, the List is filled with Float values. In the third case the list is empty, so we do not actually know what kind of values are in the list. So the type List a is saying "I know I have a list, but it could be filled with anything". The lower-case a is called a type variable, meaning that there are no constraints in our program that pin this down to some specific type. In other words, the type can vary based on how it is used.
In your case, as a first argument you should pass a function which will take a variable of type from second argument and return value of type msg.
a
is a type variable. Think of it as a placeholder that can be substituted by any other type. However, all occurences of a
in one type signature must be substituted with the same concrete type.
So if map
has this signature...
(a -> msg) -> Cmd a -> Cmd msg
...this would be a valid substitution:
(Bool -> MyMessage) -> Cmd Bool -> Cmd MyMessage
(msg
is another type variable)
...while this would be an incorrect substitution:
(Bool -> MyMessage) -> Cmd MyMessage -> Cmd Bool -- note the mismatched type variables
Having type variables gives a lot of flexibility, because a generic function like map
can be reused with all kinds of different types.
I think of it like Java generics, the a
is the generic raw type.
E.g., in java, List <String>
is a java.util.List
of String
s - this is a concrete type of List. You can also define methods with signature like List<A>
where A
is a raw generic type, where the A
is passed in by the calling method. Here is the Java explanation of raw types.
Similarly, in Elm, the List a
the a
is a place holder for a generic type.
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