gpt4 book ai didi

haskell - 实例化类时发生编译错误

转载 作者:行者123 更新时间:2023-12-02 10:54:40 25 4
gpt4 key购买 nike

class Hello a where
method1 :: a -> String
method1 a = "Hello"

data World s = World [s]

instance Hello a => World a where
method1 a = "Hello World"

将代码加载到Haskell时出现以下错误:

“method1”不是“World”类的(可见)方法

有人可以告诉我错误在哪里吗?

谢谢。

最佳答案

instance没有多大意义。在类型上定义一个实例。可能的解决方法是:

instance Hello (World a) where
method1 _ = "Hello World"
instance处理指定类型(或类型列表)在类上的映射方式,因此,如果您有带有参数 C的类 a,则可以指定:
class C a where
foo :: a -> a

现在您不需要为此花很多钱,因为您从未说过哪些 a实际上适用于 C。使用 instance,您可以指定给定类型(这些类型可以是“泛型”)适用于 C,因此接下来您可以说:
instance C a where
foo = id

在这里,您基本上可以说每种类型 a(因此所有类型)都是 C的实例。并且该 foo应该被视为 id函数。

有时您想对 a施加其他约束,例如 a应该实例化另一个类。例如与
instance (Integral i) => C i where
foo = (+) 1

在这里,您说所有整数类型 i都是 C的实例,其中 foo被定义为增量函数。 请注意,您不能简单地将此实例与上一个实例结合起来,因为Haskell不知道在这种情况下该选择哪一个。

或者也许您打算按照@bheklilr的建议定义实例:
instance (Hello a) => Hello (World a) where
method1 _ = "Hello World"

关于haskell - 实例化类时发生编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29036066/

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