'idiomatic' Haskell type inequality

后端 未结 2 1565
孤街浪徒
孤街浪徒 2021-01-14 12:15

(edited from previous question where I thought code below doesn\'t work)

I wish to implement a haskell function f that has a restriction such that its 2 parameters m

2条回答
  •  日久生厌
    2021-01-14 12:41

    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.

提交回复
热议问题