Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 类型类问题涉及;“灵活的实例”;_Haskell_Typeclass - Fatal编程技术网

Haskell 类型类问题涉及;“灵活的实例”;

Haskell 类型类问题涉及;“灵活的实例”;,haskell,typeclass,Haskell,Typeclass,给定类型类 class Dictionary w where insert :: String -> String -> w -> w remove :: String -> w -> w lookUp :: String -> w -> String 我不会写字 instance Dictionary [(String,String)] where insert key value dic = (key,value) : remov

给定类型类

class Dictionary w where
  insert :: String -> String -> w -> w
  remove :: String -> w -> w
  lookUp :: String -> w ->  String
我不会写字

instance Dictionary [(String,String)] where
  insert key value dic = (key,value) : remove key dic
  remove key dic = filter (\entry -> (fst entry) /= key) dic
  lookUp key [] = "not found"
  lookUp key ((k,v):xs) | k == key = v
                        | otherwise = lookUp key xs 
因为

Illegal instance declaration for `Dictionary[(String, String)]'
    (All instance types must be of the form (T a1 ... an)
     where a1 ... an are 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 `Dictionary[(String, String)]'
。。。我不太明白。类似这样的工作原理:

newtype Dic = Dic [(String,String)]

instance Dictionary Dic where
  insert key value (Dic dic) = Dic $ (key,value) : filter (\entry -> (fst entry) /= key) dic
  remove key (Dic dic) = Dic $ filter (\entry -> (fst entry) /= key) dic
  lookUp key (Dic []) = "not found"
  lookUp key (Dic ((k,v):xs)) | k == key = v
                              | otherwise = lookUp key (Dic xs)  

有更好的办法吗?还是应该使用建议的编译器指令

您可以使用形式为
{-#LANGUAGE FlexibleInstances}
的pragma代替编译器指令。此类杂注的范围仅限于单个模块

原因很简单。Haskell 98只允许“不饱和”类型的实例,这是在其类型变量中不固定的类型。仔细阅读它给出的错误消息,它准确地描述了编译器想要的内容

要想做你想做的事,基本上有两种方法你已经尝试过了:

  • 打开FlexibleInstances。这是最常见的方法,因为此扩展是最常用的方法之一
  • 把它包装成一个新的类型。提供兼容性,但不美观

选择一个;)

当然,但我的问题更多的是我为什么会出现这个错误,以及是否有一种不那么丑陋的方式在标准Haskell中实例化我的类型类。