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

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"

https://stackoverflow.com/questions/29036066/

相关文章:

asp.net - 错误: SignalRRouteExtension.Mapconnection

scala - 在scala中的构造函数内部调用函数

compiler-errors - ifort composer_xe_2015.3.187的编译问

compiler-errors - 由于 glib 错误,无法处理 gobject-introspe

scala - 使用 Deadbolt 2 : overriding method getSubje

c# - Unity 在编译有效的 C# 类时遇到问题

compiler-errors - 在Solaris Sparc 11下强制使用Sun Studio

jsf - ServletContext.TEMPDIR无法解析或不是字段

c# - 类数组使用产生错误 "NullReferenceException: Object ref

c# - 为什么这种编译方式有所不同?