Home > Mobile >  Why is the type for [tail, init, reverse], [[a] -> [a]]?
Why is the type for [tail, init, reverse], [[a] -> [a]]?

Time:04-19

This question is in one of the Haskell textbook exercises, not so smart question.

Question: What are the types of the following values?

[tail, init, reverse]

Solution: [[a] -> [a]]

But why?

CodePudding user response:

tail, init and reverse are functions defined on a generic list, [a]. You read [a] as "a list of any type abstracted as a", in particular, if a = Int, you get [Int] - list of integers.

Now, function that takes a list and outputs a list of the same type has signature [c] -> [c] or, if c = a, [a] -> [a]. The letter picked up does not matter as long as you have the same latter on both sides, because [a] -> [b] would mean that you take somehow a list of as and map it to a list of bs - which - in general - a different type. You could say that a = Int and b = String and therefore you'd have to map Int to String anyhow; also you could say that b = a an thus reduce to the [a] -> [a] case.

The last one: [tail, init, reverse] is obviously yet another list, where a = [b] -> [b]. So you got [ [b] -> [b] ] type or, equivalently, [ [a] -> [a] ] or [ [k] -> [k] ]. Again: particular letter does not matter as long as you stick to the chosen one.

CodePudding user response:

The type of the following value, not "values". singular. List of three elements is a value. Or did you mean "each of the values in the given list"? then they all must have the same type. since a list has a type [t] for some t. which implies all its elements have that same type t, whatever that is. then since tail :: [a] -> [a], so must be the other two that appear in the same list.

On their own they could each refer to a different letter i.e. "type variable". but inside the same list, they all must be in agreement. thus the type of the list as a whole is [ [a] -> [a] ].

  • Related