我正在尝试理解 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/