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

被刻印的时光 ゝ 提交于 2019-12-24 12:03:31

问题


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 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.


来源:https://stackoverflow.com/questions/51680886/isnt-map-takes-a-function-and-a-list-return-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!