haskell – 如何(或为什么)`Data.Set String`不是单一类型?
我正在努力学习
Haskell,尝试写一些我觉得有趣的东西,而现在我正在试图弄清楚如何在Haskell中为一组特定的解析问题推导出Semiring:
class Semiring s where zero,one :: s mul,add :: s -> s -> s instance Semiring Bool where zero = False one = True add = (||) mul = (&&) instance Semiring (Set String) where zero = empty one = singleton "" add a b = union a b mul a b = Data.Set.map ((c,d) -> c ++ d) $cartesianProduct a b Bool({true,false},∨,∧,false,true)版本效果很好. Int版本也是如此.最后一个称为Parse Forest,其表示为(E,∪,·,?,{<>}},其中E是一组字符串,{<>}是一组字符串.空字符串. 当我尝试编译时,我得到: Rigge… 115 10 error ? Illegal instance declaration for ‘Semiring (Set 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. 这对我来说没有多大意义. Set String是一个独特的类型,右,并且Semiring类的所有操作都应该纯粹以字符串集的形式表达. 如果你想要上下文,那么项目是在Rigged Regular Expressions. Bool版只报告了正则表达式匹配; Int版本报告正则表达式可以匹配的不同方式的数量(即“a”/(a | a *)/将返回2,因为两个不同且唯一的子表达式匹配); ParseForest应该返回的不是方式的数量,而是所有可能的方式的集合 – 但它不能,因为我不明白为什么我不能使用具体的数据类型,Set String,其中另一个具体的数据类型如Int或Bool工作正常. 解决方法
关键部分是
of the form (T a1 ... an) where a1 ... an are *distinct type variables*, 你的类型是Set String,所以T = Set,a1 = String(和n = 1).但String是一种类型,而不是类型变量.相反,一个合规的实例 instance (....) => Semiring (Set a) where ... 无论如何,这是Haskell2010的一个古老限制,你可以忽略它.在现代GHC Haskell中,您可以打开FlexibleInstances扩展,并使用您自己的实例而不会出现问题. GHC本身应该建议在错误消息中打开它. 请注意,现在几乎没有人在严格的Haskell2010中编程:有太多的扩展已经变得太常用了.可以说,应该对报告进行修订,例如Haskell2020,其中大多数常见的无害扩展都包括在内.不过,在有人真正这样做之前,我们需要经常打开扩展程序. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |