I’m currently trying to learn Haskell, but I’m struggling with understanding the syntax. For example, take the map function:
map :: (s -> t) -> [s] -> [t]
map f [] = []
map f (x:xs) = f x : map f xs
I understand what the function does, and that map has a function f :: s -> t as a parameter. But I read map :: (s -> t) -> [s] -> [t] as “map is a function which maps a function mapping from s to t to s and then to t”, which is obviously wrong. Could someone clear this up for me?
The type
(s -> t) -> [s] -> [t]can be read in two ways. One way is to treat it as a function of two arguments, the first a function of types -> tand the second a list of type[s]. The return value is of type[t].The other way is to understand that function arrows are right-associative, so the type is equivalent to
(s -> t) -> ([s] -> [t]). Under this interpretation,mapis a function that takes a function from element to elements -> tand turns it into a function from list to list[s] -> [t].Similarly, when using the function, you can think of
map foo xsas applying the functionmapto two argumentsfooandxs. Or, since function application is left-associative, you can think of it as(map foo) xs, applyingmapto the single argumentfooto get back a new function which you then apply toxs.Since Haskell functions are curried, these are just two ways of looking at the exact same thing.