Infer constraints for both if and else of type equality

守給你的承諾、 提交于 2019-12-24 05:29:35

问题


I am trying to fill the hole in the following snippet

import Data.Proxy
import GHC.TypeLits
import Data.Type.Equality
import Data.Type.Bool
import Unsafe.Coerce

ifThenElse :: forall (a :: Nat) (b :: Nat) x l r.
  (KnownNat a, KnownNat b, x ~ If (a==b) l r) =>
  Proxy a -> Proxy b -> Either (x :~: l) (x :~: r)
ifThenElse pa pb = case sameNat pa pb of
  Just Refl -> Left Refl
  Nothing -> Right $ unsafeCoerce Refl -- This was the hole

Is it possible?

Edit: Checked the source of sameNat and it turns out they use unsafeCoerce. I edited the code above accordingly.


回答1:


One possible solution is to use the singletons library to get term-level functions representing the type-level ones (or vice-versa).

The gist of it is:

import Data.Singletons.Prelude

(...)

case (sing :: Sing a) %:== (sing :: Sing b) of
  STrue  -> Left Refl
  SFalse -> Right Refl

I've put up a self-contained file with all the imports and language extensions too.



来源:https://stackoverflow.com/questions/42240533/infer-constraints-for-both-if-and-else-of-type-equality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!