的获得I型有型哈斯克尔代数参数
class IntegerAsType a where
value :: a -> Integer
data T5
instance IntegerAsType T5 where value _ = 5
newtype (IntegerAsType q) => Zq q = Zq Integer deriving (Eq)
newtype (Num a, IntegerAsType n) => PolyRing a n = PolyRing [a]
我试图做的PolyRing型一个不错的“秀”。特别是,我想让“秀”打印出型号'a'。是否有一个函数返回代数参数的类型(类型为'show')?
我试图做的另一种方式是使用模式匹配,但我遇到了内置类型和代数类型的问题。
我想为Integer,Int和Zq q中的每一个获得不同的结果。 (例如玩具:)
test :: (Num a, IntegerAsType q) => a -> a
(Int x) = x+1
(Integer x) = x+2
(Zq x) = x+3
这里有至少两个不同的问题。
1)Int和Integer不是'Int'和'Integer'类型的数据构造函数。是否有这些类型的数据构造函数/如何模式匹配?
2)虽然在我的代码中没有显示,但Zq是Num的一个实例。我得到的问题是:
Ambiguous constraint `IntegerAsType q'
At least one of the forall'd type variables mentioned by the constraint
must be reachable from the type after the '=>'
In the type signature for `test':
test :: (Num a, IntegerAsType q) => a -> a
我有点看到它为什么抱怨,但我不知道如何解决这个问题。
感谢
编辑: 的什么,我试图与测试功能做一个更好的例子:
test :: (Num a) => a -> a
test (Integer x) = x+2
test (Int x) = x+1
test (Zq x) = x
即使我们忽略了一个事实,我不能构建整数和INTS这种方式(仍想知道如何!),这种“测试”并没有编译,因为:
Could not deduce (a ~ Zq t0) from the context (Num a)
我的下一次尝试在此功能与类型签名:
test :: (Num a, IntegerAsType q) => a -> a
从而导致新的错误
Ambiguous constraint `IntegerAsType q'
At least one of the forall'd type variables mentioned by the constraint
must be reachable from the type after the '=>'
我希望这是我的问题更清楚一点....
hammar回答了我的问题的第一部分。不过,我仍然对如何进行模式匹配感兴趣。你可以在Int和Integer模式匹配吗? – crockeea
我欣赏这个警告,并意识到我可能正在挖一个洞... 让我试着给一个函数的更好的例子,我可能实际上需要我所要求的: test::(Num a)=> a - > a test(Int x)= x + 2 test (Zq x)的类型参数,所以我可以修改,如果我需要。更重要的是,它不会编译(即使我拿出不可构造的Int和Integer行)。随着类型签名给定的,我得到的错误:从上下文(民一) 无法推断(一〜ZQ T0) – crockeea
似乎有在这里是一些误解关于类型。给我几分钟,我会更新我的答案,讨论我能做些什么。 –