Map Function using list implementation haskell

依然范特西╮ 提交于 2019-12-13 09:47:15

问题


Is there a way to write an implementation of the Haskell map function using list implementation?

I keep getting an error and I do not think I am on the right track. This is what I have:

map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' xs ys = [ (x, y) | x <- xs | y <- ys ]

Any help or link that will guide me in the right direction would be much appreciated.


回答1:


I believe you mean "comprehension", instead of "implementation".

Either way, this would work:

map' f as = [f a | a <- as]
map' (* 2) [1..5]



回答2:


Note that

map' f xs = [f x | x <- xs]

desugars to

map' f xs = do x <- xs
               return $ f x

which desugars to

map' f xs = xs >>= return . f

which is the well-known definition (if you replace map' with fmap) for defining a Functor instance from a Monad instance (thus proving that all monads are also functors).

Specifically, it shows that a list comprehension is simply a disguised version of the definition of map in terms of monadic operators.



来源:https://stackoverflow.com/questions/46876549/map-function-using-list-implementation-haskell

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