[英]Typeclass instance with arithmetic constraints on types
基本上,我希望能够做到这样的事情:
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
import GHC.TypeLits
newtype Foo (a::Nat) (b::Nat) c = Foo {getFoo :: c}
class Clz a where
instance Clz (Foo a (2*a) c) where
即,仅当a = 2*b
时才使Foo ab
成为Clz
实例。
我知道问题(2*a)
在最后一行的(2*a)
表达式中。 当我尝试编译它时,我得到:
• Illegal type synonym family application in instance:
Foo a (2 * a) c
• In the instance declaration for ‘Clz (Foo a (2 * a) c)’
有办法克服这个问题吗? 我如何更改语法? 我需要更多语言扩展吗? 我正在使用最新的GHC(8.0.1)。
您可以使用类型等价约束(通过启用GADT或键入族):
instance (b ~ (2 * a)) => Clz (Foo a b c) where
这是处理类型族的常用技术,如另一个答案所示 。 这个答案有更多的解释:这个约束并不意味着你想要的版本完全相同 ,但可能仍然适合你的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.