Doing homework I found myself stuck with a problem. I have to go from a basic type to a "more complex" one by unifying them (the professor calls it unifying them). An example with map map:
map :: (c -> d) -> [c] -> [d]
map :: (a -> b) -> [a] -> [b]
By replacing c
with a -> b
, and d
with [a] -> [b]
and omitting the first parameter of map, the result is [a -> b] -> [[a] -> [b]]
which is what haskell returns when doing :t map map.
On one excercise I have [length, head]
which according to :t in Haskell [length, head] :: [[Int] -> Int]
I'm having issues understanding how [length, head]
works. It is a list of functions? It performs head
to a list and then length
is applied to the result?
I couldn't find an example of this working and every time i tried to input a list or list of lists to [length,head]
it ends up in error. I noticed that [head,length]
has the same type as [length,head]
which did not help me understand it.
How is [length,head]
supposed to work?
I'm having issues understanding how
[length, head]
works. It is a list of functions?
Yes, it is a list with two elements, both of these elements are functions.
It performs
head
to a list and thenlength
is applied to the result?
No. It is simply a list with two functions, just like you can have a list of two Char
s, or two String
s, you can have a list of two functions. In Haskell functions are first class citizens, you can pass these as parameters, and return these as the result of a function. The elements in a list however always are of the same type. So that means that the length
and the head
in the list need to be of the same type.
This thus means that head :: [a] -> a
, and length :: [b] -> Int
need to be of the same type, and thus we can say that [a] -> a
and [b] -> Int
should be the same type. This implies that a ~ Int
(since the return type of both functions is the same), and a ~ b
(since the input type of the two types is the same), so as a result, the type of the two functions is [Int] -> Int
.
So for this list, the head
and the length
have as type [Int] -> Int
. It thus means that the list of these two functions has type [[Int] -> Int]
.
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