'idiomatic' Haskell type inequality

帅比萌擦擦* 提交于 2019-12-01 09:20:42

With new features being added to GHC, you'll be able to write:

{-# LANGUAGE DataKinds, PolyKinds, TypeFamilies #-}

type family Equal (a :: k) (b :: k) :: Bool
type instance where
   Equal a a = True
   Equal a b = False

This is how it is done in the HList library

{-# LANGUAGE FlexibleInstances, 
    MultiParamTypeClasses, 
    FunctionalDependencies, 
    UndecidableInstances ,
    IncoherentInstances
 #-}

data HTrue; data HFalse;

class TypeCast a b | a -> b
instance TypeCast a a

class TypeEq a b c | a b -> c
instance TypeEq x x HTrue
instance (TypeCast HFalse b) => TypeEq x y b
-- instance TypeEq x y HFalse -- would violate functional dependency

You can fully infer type equality now:

typeEq :: TypeEq a b c => a -> b -> c
typeEq _ _ = undefined

Note that typeEq 0 1 == HFalse since 0 :: Num a => a and 1 :: Num b => b.

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