我正在阅读《Programming in Haskell》第二版,我看到了这句话:
... there is only one way to make any given parameterised type into a functor, and hence any function with the same polymorphic type as
fmap
must be equal tofmap
.
不过,这对我来说似乎不太合适。我可以看到,对于每个 Functor
类型,只有一个 有效 fmap 定义,但我肯定可以使用该类型定义任意数量的函数(a -> b) -> f a -> f b
彼此不等价?
为什么会出现这样的情况呢?或者,这只是作者的错误?
最佳答案
你误读了作者所说的内容。
...any function with the same polymorphic type as
fmap
...
这意味着任何带有签名的函数
Functor f => (a -> b) -> f a -> f b
必须等于 fmap
。 (当然,除非您允许底值。)
这个说法是正确的;如果你尝试定义这样一个函数,就很容易看出:因为你对f
一无所知。除了它是一个仿函数之外,获得非⊥ f b
的唯一方法值是通过对 f a
进行 fmapping 得到的一个。
引文中的逻辑含义不太明确:
there is only one way to make any given parameterised type into a functor, and hence any function with the same polymorphic type as fmap must be equal to fmap.
我认为作者的意思是存在的,因为 Functor f => (a -> b) -> f a -> f b
函数必须调用fmap
,并且因为 fmap
始终是参数化类型的唯一有效仿函数映射,任何 Functor f => (a -> b) -> f a -> f b
实际上也会遵守仿函数定律,即它将是 fmap
.
我同意“因此”的措辞有点糟糕,但原则上引用是正确的。
关于haskell - 任何与 fmap 具有相同多态类型的函数都必须等于 fmap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55691337/