问题
I'm wondering where I can find information about the "a" used in the Length example. It seems to be a type of some kind?
回答1:
[1,2,3] is a List Int, functions that could only work with a Lists of Ints would have to have List Int in their type signature. ["a", "b"] is a List String, functions that could only work with a Lists of Strings would have to have List String in their type signature. A function that works with a list of any type (for example List.length) can have a generic type signature (like List a or List b). The meaning of a is only relevant within the type signature. For example a function with a type of List a -> a, when given a List Int would return an Int. When given a List String it would return a String.
Take for example the map function which has a signature of (a -> b) -> List a -> List b. It says that given a function that takes an a and returns a b, and a List a, it will return a List b.
Given a function that takes a String and returns an Int, and a List String, map will return a List Int.
List.map String.length ["a", "aa", "aaa"]
-- [1, 2, 3] : List Int
Given a function that takes an Int and returns a String, and a List Int, map will return a List String.
List.map (\n -> String.repeat n "a") [1, 2, 3]
-- ["a", "aa", "aaa"] : List String
回答2:
a is a type variable.
This means that the type List is polymorphic (generic), i.e. a can be substituted by any type (Int, String, ...). The function length is polymorphic too. For example, length [1, 2, 3] will return 3, length ["word1", "word2"] will return 2.
来源:https://stackoverflow.com/questions/31268051/what-is-the-a-in-list-a-in-the-length-example