Elm docs - What does "a" mean?

Elm docs do not use a usage example, so it’s hard to understand what type specifications mean. In several places, I saw "a" used as the identifier of the argument, for example, in Platform.Cmd :

map : (a -> msg) -> Cmd a -> Cmd msg 

What does it mean? How to use Cmd.map ?

+5
source share
3 answers

a is a type variable. Think of it as one that can be replaced with any other type . However, all occurrences of a in a signature of the same type must be replaced by the same specific type.

So, if map has this signature ...

 (a -> msg) -> Cmd a -> Cmd msg 

... that would be a valid substitution:

 (Bool -> MyMessage) -> Cmd Bool -> Cmd MyMessage 

( msg is another type variable)

... although this would be a wrong replacement:

 (Bool -> MyMessage) -> Cmd MyMessage -> Cmd Bool -- note the mismatched type variables 

The presence of type variables provides great flexibility, because a generic function of type map can be reused with all types of different types.

+4
source

Here is part of Annotations Type Reading Guide :

 > [ "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. secondly, the List is populated with Float values. In the third case, the list is empty, so we actually do not know what values ​​are in the list. So, the type of List a says: "I know that I have a list, but it can be filled with anything." Lowercase a is called a type variable, which means that there are no restrictions in our program, bind this to a specific type. In other words, the type may vary based on how it is used.

In your case, as the first argument, you must pass a function that takes a type variable from the second argument and returns a value of type msg.

+5
source

I think of it as Java generation, a is a generic type of raw.

For example, in java, List <String> is java.util.List of String is a specific type of List. You can also define methods with a signature of type List<A> , where a is a raw common type, where a is passed in by the calling method. Here is an explanation of Java source types .

Similarly, in the Elm List a the a is a place holder for the generic type.

+2
source

Source: https://habr.com/ru/post/1265256/


All Articles