Associated Parameter Restriction using Functional Dependency

前端 未结 3 814
走了就别回头了
走了就别回头了 2021-01-21 21:54

The function f below, for a given type \'a\', takes a parameter of type \'c\'. For different types \'a\', \'c\' is restricted in different ways. Concretely, when \'a\' is any In

3条回答
  •  长情又很酷
    2021-01-21 22:44

    A possibly better way, is to use constraint kinds and type families (GHC extensions, requires GHC 7.4, I think). This allows you to specify the constraint as part of the class instance.

    {-# LANGUAGE ConstraintKinds, TypeFamilies, FlexibleInstances, UndecidableInstances #-}
    
    import GHC.Exts (Constraint)
    
    class Foo a where
       type ParamConstraint a b :: Constraint
       f :: ParamConstraint a b => b -> a
    
    instance Integral i => Foo i where
       type ParamConstraint i b = Real b
       f = fIntegral
    

    EDIT: Upon further experimentation, there are some subtleties that mean that this doesn't work as expected, specifically, type ParamConstraint i b = Real b is too general. I don't know a solution (or if one exists) right now.

提交回复
热议问题