如何扩展ghc-typelits-natnormalise来检查普遍和存在量化类型之间的关系?

时间:2018-02-09 18:43:54

标签: haskell types proxy ghc existential-type

我正在尝试使用Finite代替Proxy来完全安全且非局部地使用Integer

-- SO test case, re: my use of ghc-typelits-natnormalise package.
--
-- David Banas <capn.freako@gmail.com>
-- February 9, 2018

{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}

module Bogus.NewFin where

import GHC.TypeLits
import Data.Proxy
import Data.Finite
import Data.Finite.Internal (Finite(..))
import Data.Reflection

-- A safer form of `finite`.
finite' :: (KnownNat n, KnownNat m, n `CmpNat` m ~ 'GT) => Proxy m -> Finite n
finite' p = Finite $ natVal p

-- A safer form of `getFinite`.
getFinite' :: KnownNat n => Finite n -> (forall m. (KnownNat m, n `CmpNat` m ~ 'GT) => Proxy m -> r) -> r
getFinite' x f = reifyNat (getFinite x) f

我收到了这个编译错误:

Davids-Air-2:test dbanas$ stack ghc -- -c so_natnorm.hs 

so_natnorm.hs:28:41: error:
    • Couldn't match type ‘CmpNat n n1’ with ‘'GT’
        arising from a use of ‘f’
    • In the second argument of ‘reifyNat’, namely ‘f’
      In the expression: reifyNat (getFinite x) f
      In an equation for ‘getFinite'’:
          getFinite' x f = reifyNat (getFinite x) f
    • Relevant bindings include
        f :: forall (m :: Nat).
             (KnownNat m, CmpNat n m ~ 'GT) =>
             Proxy m -> r
          (bound at so_natnorm.hs:28:14)
        x :: Finite n (bound at so_natnorm.hs:28:12)
        getFinite' :: Finite n
                      -> (forall (m :: Nat).
                          (KnownNat m, CmpNat n m ~ 'GT) =>
                          Proxy m -> r)
                      -> r
          (bound at so_natnorm.hs:28:1)

我猜测我的问题是试图通过 ghc-typelits-natnormalise 包提供的机制来关联普遍存在和存在量化的类型。这是对的吗?

在我看来,这应该被允许,因为来电者负责分配两者:

  • n
  • 的值
  • m的最大值。

我对这个错误的推理在哪里?

1 个答案:

答案 0 :(得分:1)

reifyNat将一个适用于任何自然的函数作为参数。 forall m. (KnownNat m, n `CmpNat` m ~ 'GT) => Proxy m -> r类型的函数不适用于任何自然类型;它只适用于少于其他n的自然物。

由于您要调用getFinite来生成实际值,因此您知道该值小于n。不幸的是,你没有办法向typechecker证明这一点。幸运的是,你可以告诉typechecker相信你:

import Type.Reflection ((:~:)(..))
import Unsafe.Coerce

...

getFinite'' :: KnownNat n => Finite n -> (forall m. (KnownNat m) => Proxy m -> n `CmpNat` m :~: 'GT -> r) -> r
getFinite'' x f = reifyNat (getFinite x) $ \p -> f p (unsafeCoerce Refl)

getFinite' :: forall n r . KnownNat n => Finite n -> (forall m. (KnownNat m, n `CmpNat` m ~ 'GT) => Proxy m -> r) -> r
getFinite' x f = getFinite'' x $ \p Refl -> f p