How to put constraints on the associated data?

后端 未结 3 1376
温柔的废话
温柔的废话 2021-02-19 06:43

I would like to state that the associated data is always an instance of a certain class.

class (Context (Associated a b)) => Class a where
  data Associated a         


        
3条回答
  •  遇见更好的自我
    2021-02-19 06:54

    One idiomatic way is to create a Context1 class. Supposing we have

    class Context a where
        func :: a -> String
    

    we might generalize as:

    class Context1 f where
        func1 :: Context a => f a -> String
    

    Then you give a single instance for all Associateds:

    instance (Context1 (Associated a), Context b) => Context (Associated a b) where
        func = func1
    

    Now it is easy to write the class you want as

    instance Context1 (Associated a) => Class a where
        data Associated a :: * -> *
    

    and you can be sure that the given Context1 (Associated a) context ensures the desired forall b. Context b => Context (Associated a b) context.

    There are many examples of this pattern on Hackage, like Show1, Foldable1, and Traversable1.

提交回复
热议问题