Isn't map takes a function and a list return a

2019-07-25 07:27发布

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条回答
走好不送
2楼-- · 2019-07-25 07:59

"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 function f :: a -> b -> c is applied to an a and returns a function b -> c
  • bs is the second list from map2_List
  • The result of this function is [c], the function f applied to one element of the first list then applied to every element of the second list.
查看更多
登录 后发表回答