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

标签 list haskell monads redundancy functor

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/

相关文章:

haskell - 检查自由单子(monad) AST 中的绑定(bind)结构

C 和 Haskell 中整数的组合

terminology - 术语 "monad"是否适用于 Maybe 或 List 等类型的值,还是仅适用于类型本身?

scala Iterable#map 与 Iterable#flatMap

Java索引越界异常索引:2,大小:2

c# - 如何在 ASP.NET 数据列表中放置一个列表

c++ - 我的反向单链表函数代码有什么问题?

python - 如何比较两个列表以保持匹配的子字符串?

haskell - Haskell 中的融合是什么?

monads - 使用 getTime 函数时出现问题