gpt4 book ai didi

haskell - 使用两个相同类型类实现自定义数据类型的应用仿函数

转载 作者:行者123 更新时间:2023-12-02 13:46:14 25 4
gpt4 key购买 nike

我试图使 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>

请注意,您仍然需要通过考虑为这些类型类记录的约束来证明这是一个有效的 FunctorApplicative 实例。

关于haskell - 使用两个相同类型类实现自定义数据类型的应用仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358348/

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