问题
map2_List :: (a -> b -> c) -> [a] -> [b] -> [c]
map2_List f [] _ = []
map2_List f (a:as) bs = map (f a) bs ++ map2_List f as bs
This is an example from my lecture, which try to apply a binary function to all pairs of elements of two lists. The part (f a)
makes me confused. Does it suppose to be a value but not a function? Then what does map value bs
do?
回答1:
"The part (f a)
makes me confused."
What is happening here is called currying and if you are coming to Haskell from imperative languages, it can be confusing.
In Haskell, all functions technically take a single value and return a single value. The returned value could be another function. Most programmers take the mental shortcut of thinking of functions taking all the values in their definition (the term is "saturated" BTW) and producing the final value, but even with this mental shortcut, there are a lot of times, like this, when it is not the case.
The function f
is a binary function, and (f a)
is that function partially applied. The type of (f a) :: b -> c
.
"Then what does
map value bs
do?"
The map function (map :: (a->b) -> [a] ->[b]
) is part of the standard prelude. It takes a simple function and applies it to each element in a list.
So let's take map (f a) bs
apart:
- map :: (b->c) -> [b] ->[c] applies a function to each element of a list
(f a) :: b -> c
using currying a functionf :: a -> b -> c
is applied to ana
and returns a functionb -> c
bs
is the second list frommap2_List
- The result of this function is
[c]
, the functionf
applied to one element of the first list then applied to every element of the second list.
来源:https://stackoverflow.com/questions/51680886/isnt-map-takes-a-function-and-a-list-return-a-list