在回答我的问题之前,让我陈述一下我的理解(也许是不正确的),即列表[]是一种更友好的类型:
ghci> :kind []
[] :: * -> *我可能弄错了,但是,[]需要一种类型,因为它是List of some type 'T'。
现在来回答我的问题。
class Foo a where
bar :: String -> a然后,我尝试创建一个Foo [String]。我的理解是,a in Foo a是[String]。因此,我希望bar返回一个[String]。
instance Foo [String] where
bar [] = []
bar (x:_) = [x]但是,我得到了以下编译时错误:
ghci> :l TypeClassExample.hs
[1 of 1] Compiling Main ( TypeClassExample.hs, interpreted )
TypeClassExample.hs:5:10:
Illegal instance declaration for `Foo [String]'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Foo [String]'
Failed, modules loaded: none.我犹豫不决地添加这个编译时标志而不理解它。
在这个简单的代码中,它的意义是什么?
发布于 2014-10-09 13:52:48
Haskell语言定义的限制性很强,只允许列表实例的形式。
instance ... => Foo [a] where在头部,a恰好是一个类型变量a,不允许使用[Int]或[String]。
但是,您可以要求GHC忽略此限制。只需在文件开头添加以下内容:
{-# LANGUAGE FlexibleInstances #-}许多,许多现代Haskell程序都利用了这一点。可以说,在下一个Haskell定义修订版中,这个GHC特性应该被集成。
https://stackoverflow.com/questions/26279195
复制相似问题