class - 无法使 String 成为 Haskell 中的类的实例

标签 class haskell

我正在尝试理解 Haskell 中的类。
我写了几行愚蠢的代码来掌握它。我写了一个名为 Slang 的类有一个功能。当我将 Integer 作为我的类的实例时,它工作正常。但是当我将 String 作为我的类的实例时,它不会编译。我一直在根据错误输出告诉我的内容对程序坐立不安,但无济于事。我知道它为什么起作用...

这是错误后面的代码:

module Practice where

class Slang s where
    slangify :: s -> String

instance Slang Integer where
    slangify int = "yo"

instance Slang String where  -- When I take this segment out, it works fine
    slangify str = "bro"

错误:
Prelude> :load Practice
[1 of 1] Compiling Practice         ( Practice.hs, interpreted )

Practice.hs:9:10:
    Illegal instance declaration for `Slang String'
      (All instance types must be of the form (T t1 ... tn)
       where T is not a synonym.
       Use -XTypeSynonymInstances if you want to disable this.)
    In the instance declaration for `Slang String'
Failed, modules loaded: none.
Prelude>

最佳答案

问题是 String 不是像 Integer 这样的基本类型。你想要做的实际上是

instance Slang [Char] where
    slangify str = "bro"

然而,Haskell98 禁止这种类型的类型类,以使事情变得简单,并使人们更难编写重叠的实例,例如
instance Slang [a] where
    -- Strings would also fit this definition.
    slangify list = "some list"

无论如何,正如错误消息所暗示的,您可以通过启用 FlexibleInstances 来绕过此限制。扩大。

关于class - 无法使 String 成为 Haskell 中的类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285822/

相关文章:

java - Groovy - 主要方法放置

javascript - 如何在类中设置局部变量

c++ - 使用继承类型调用基类函数

windows - 无法加载 OpenGL 进程,只能从 Haskell 加载

c++ - 非 constexpr 类的 Constexpr 方法

python - 如何正确扩展 Python 中的其他类? ( python v3.3)

Haskell Char 和 unicode 代理

haskell - 排名多态性和离谱财富的 kleisli 箭头

Haskell 状态 monad 在偶数和奇数函数调用上的不同行为

haskell - 成功导入的数据构造函数不在范围内?