gpt4 book ai didi

haskell - 无法在关于单例库的两个存在中推断 KnownNat

转载 作者:行者123 更新时间:2023-12-01 15:10:04 25 4
gpt4 key购买 nike

我正在试验单例库,发现一个我不明白的案例。

{-# LANGUAGE GADTs, StandaloneDeriving, RankNTypes, ScopedTypeVariables,
FlexibleInstances, KindSignatures, DataKinds, StandaloneDeriving #-}

import Data.Singletons.Prelude
import Data.Singletons.TypeLits

data Foo (a :: Nat) where
Foo :: Foo a
deriving Show

data Thing where
Thing :: KnownNat a => Foo a -> Thing

deriving instance Show Thing

afoo1 :: Foo 1
afoo1 = Foo

afoo2 :: Foo 2
afoo2 = Foo

athing :: Thing
athing = Thing afoo1

foolen :: forall n. KnownNat n => Foo n -> Integer
foolen foo =
case sing of (SNat :: Sing n) -> natVal (Proxy :: Proxy n)


minfoo :: forall a b c. (Min a b ~ c, KnownNat c) => Foo a -> Foo b -> Integer
minfoo _ _ =
let c = case sing of (SNat :: Sing c) -> natVal (Proxy :: Proxy c)
in natVal (Proxy :: Proxy c)

thinglen :: Thing -> Integer
thinglen (Thing foo) = foolen foo

我可以用它来获得最少的两件事
minthing :: Thing -> Thing -> Integer
minthing (Thing foo1) (Thing foo2) = min (foolen foo1) (foolen foo2)

但是为什么我不能这样做呢?
minthing' :: Thing -> Thing -> Integer
minthing' (Thing foo1) (Thing foo2) = minfoo foo1 foo2

• Could not deduce (KnownNat
(Data.Singletons.Prelude.Ord.Case_1627967386
a
a1
(Data.Singletons.Prelude.Ord.Case_1627967254
a a1 (GHC.TypeLits.CmpNat a a1))))

最佳答案

你需要做一些定理证明来检查给定的 KnownNat aKnownNat b你可以得到KnownNat (Min a b) .一个可能的解决方案:

import Data.Constraint

(...)
theorem :: forall a b. (KnownNat a, KnownNat b) =>
Sing a -> Sing b -> Dict (KnownNat (Min a b))
theorem sa sb = case sCompare sa sb of
SLT -> Dict
SEQ -> Dict
SGT -> Dict

fooSing :: forall a. KnownNat a => Foo a -> Sing a
fooSing _ = sing

minthing' :: Thing -> Thing -> Integer
minthing' (Thing foo1) (Thing foo2) =
case theorem (fooSing foo1) (fooSing foo2) of
Dict -> minfoo foo1 foo2

关于haskell - 无法在关于单例库的两个存在中推断 KnownNat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41492754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com