问题
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