作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图使 Twice 成为 applicative 的成员,但我在仿函数实现中遇到“'a'的定义冲突”:此外,我不确定如何正确实现 <*> :/
data Twice a = Twice a a deriving (Show)
instance Functor Twice where
fmap f (Twice a a) = Twice (f a) (f a)
instance Applicative Twice where
pure x = (Twice x) x
Twice f f <*> Twice x x = Twice ((f x) (f x))
最佳答案
我猜这些错误更多是语法上的而不是语义上的。在你的定义中:
Twice <b>f</b> <b>f</b> <*> Twice <b>x</b> <b>x</b> = Twice ((f x) (f x))
与Functor
定义相同:
fmap f (Twice <b>a</b> <b>a</b>) = Twice (f a) (f a)
你在头部写了两个f
和两个x
。 Haskell 不允许这样做(Prolog 允许,但即便如此,它也可能不是你的意思)。
此外,您在正文中写道:
((f x) (f x))
这意味着您将使用 f x
函数和 f x
参数进行函数调用,这可能又不是您想要的。
我们可以在语法上将其修复为:
instance Functor Twice where
fmap f (Twice a <b>b</b>) = Twice (f a) (f <b>b</b>)
instance Applicative Twice where
pure x = Twice x x
Twice <b>f</b> <b>g</b> <*> Twice <b>x</b> <b>y</b> = Twice <b>(f x) (g y)</b>
请注意,您仍然需要通过考虑为这些类型类记录的约束来证明这是一个有效的 Functor
和 Applicative
实例。
关于haskell - 使用两个相同类型类实现自定义数据类型的应用仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358348/
我是一名优秀的程序员,十分优秀!