类型家庭不减少与GHC

时间:2019-01-11 14:35:31

标签: haskell types

我正在使用类型级别的Nats,并且希望将比率降低为最简单的术语:

a = TC 1 2 :: TC 1 2
b = TC 2 3 :: TC 2 3

如果我有两个不同的术语:

norm a :: TC 1 2

norm b :: TC 
    (GHC.TypeNats.Div 2 (GHC.TypeLits.Extra.GCD 2 3)) 
    (GHC.TypeNats.Div 3 (GHC.TypeLits.Extra.GCD 2 3))

然后:

norm (TC 2 3 :: TC 2 3) :: TC 2 3

这类似于question,但是在我的情况下,类型检查不会强制减少:

* Couldn't match type `GHC.TypeNats.Div
                         3 (GHC.TypeLits.Extra.GCD 2 3)'
                 with `3'

失败:

{{1}}

1 个答案:

答案 0 :(得分:3)

您可能忘记了启用插件。编译如下:

{-# OPTIONS_GHC -fplugin GHC.TypeLits.Extra.Solver #-}
{-# LANGUAGE DataKinds, KindSignatures, TypeFamilies, UndecidableInstances #-}

import GHC.TypeLits
import GHC.TypeLits.Extra

data TC (n::Nat) (d::Nat) = TC Int Int deriving (Eq, Show)

type family Norm (n::Nat) (d::Nat) ::(Nat, Nat) where
    Norm n d = '(Div n (GCD n d), Div d (GCD n d))

norm  :: Norm n d ~ '(np, dp) => TC n d -> TC np dp
norm (TC a b) = TC (div a (gcd a b)) (div b (gcd a b))

a = TC 1 2 :: TC 1 2
b = TC 2 3 :: TC 2 3

b' = norm (TC 2 3 :: TC 2 3) :: TC 2 3