且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过Nat-kind重叠实例

更新时间:2023-11-01 09:13:04

添加Bounded (Symmetric (n-1))Enum (Symmetric (n-1))作为约束,因为要完全解决这些约束将需要知道n的确切值.

Add Bounded (Symmetric (n-1)) and Enum (Symmetric (n-1)) as constraints, because fully resolving those constraints would require knowing the exact value of n.

instance (KnownNat n, 2 <= n, Bounded (Symmetric (n-1)), Enum (Symmetric (n-1))) =>
  Enum (Symmetric n) where
  ...

instance (KnownNat n, 2 <= n, Bounded (Symmetric (n-1))) =>
  Bounded (Symmetric n) where
  ...


要避免使用FlexibleInstances(这对IMO来说不值得,FlexibleInstances是一个良性扩展),请使用Peano数字data Nat = Z | S Nat代替GHC的原始表示形式.首先用Bounded (Symmetric (S (S n')))替换实例头Bounded (Symmetric n)(这扮演约束2 <= n的角色),然后使用辅助类(可能更多)分解实例,以满足实例头的标准要求.可能看起来像这样:


To avoid FlexibleInstances (which is not worth it IMO, FlexibleInstances is a benign extension), use Peano numbers data Nat = Z | S Nat instead of GHC's primitive representation. First replace the instance head Bounded (Symmetric n) with Bounded (Symmetric (S (S n'))) (this plays the role of the constraint 2 <= n), and then break up the instance with an auxiliary class (possibly more) to satisfy the standard requirement on instance heads. It might look like this:

instance Bounded_Symmetric n => Bounded (Symmetric n) where ...
instance Bounded_Symmetric O where ...
instance Bounded_Symmetric n => Bounded_Symmetric (S n) where ...