Are type synonyms with typeclass constraints possible?

后端 未结 2 960
囚心锁ツ
囚心锁ツ 2021-01-19 00:18

Feel free to change the title, I\'m just not experienced enough to know what\'s really going on.

So, I was writing a program loosely based on this, and wrote this (a

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 01:11

    Usually you want to avoid having constraints in your type synonyms unless it's really necessary. Take the Data.Set API from containers for example.

    Many operations in Data.Set require the elements of the set to be instances of Ord because Set is implemented internally as a binary tree. member or insert both require Ord

    member :: Ord a => a -> Set a -> Bool
    insert :: Ord a => a -> Set a -> Set a
    

    However the definition of Set doesn't mention Ord at all.

    This is because some operations on Set dont require an Ord instance, like size or null.

    size :: Set a -> Int
    null :: Set a -> Bool
    

    If the type class constraint was part of the definition of Set, these functions would have to include the constraint, even though it's not necessary.

    So yes, it is possible to have constraints in type synonyms using RankNTypes, but it's generally ill-advised. It's better to write the constraint for the functions that need them instead.

提交回复
热议问题