gpt4 book ai didi

list - 为什么我们有map、fmap和liftM?

转载 作者:行者123 更新时间:2023-12-03 04:49:05 25 4
gpt4 key购买 nike

map :: (a -> b) -> [a] -> [b]

fmap :: Functor f => (a -> b) -> f a -> f b

liftM :: Monad m => (a -> b) -> m a -> m b

为什么我们有三个不同的函数,但本质上是做同样的事情?

最佳答案

map 的存在是为了简化列表上的操作以及出于历史原因(请参阅 What's the point of map in Haskell, when there is fmap? )。

You might ask why we need a separate map function. Why not just do away with the current list-only map function, and rename fmap to map instead? Well, that’s a good question. The usual argument is that someone just learning Haskell, when using map incorrectly, would much rather see an error about lists than about Functors.

--Typeclassopedia ,第 20 页

fmapliftM 之所以存在,是因为 monad 在 Haskell 中并不是自动仿函数:

The fact that we have both fmap and liftM is an unfortunate consequence of the fact that the Monad type class does not require a Functor instance, even though mathematically speaking, every monad is a functor. However, fmap and liftM are essentially interchangeable, since it is a bug (in a social rather than technical sense) for any type to be an instance of Monad without also being an instance of Functor.

--Typeclassopedia ,第 33 页

编辑:agustuss 的 mapfmap 历史:

That's not actually how it happens. What happened was that the type of map was generalized to cover Functor in Haskell 1.3. I.e., in Haskell 1.3 fmap was called map. This change was then reverted in Haskell 1.4 and fmap was introduced. The reason for this change was pedagogical; when teaching Haskell to beginners the very general type of map made error messages more difficult to understand. In my opinion this wasn't the right way to solve the problem.

--What's the point of map in Haskell, when there is fmap?

关于list - 为什么我们有map、fmap和liftM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7463500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com