Why constraints on data are a bad thing?

前端 未结 3 1022
深忆病人
深忆病人 2021-02-18 18:20

I know this question has been asked and answered lots of times but I still don\'t really understand why putting constraints on a data type is a bad thing.

For example, l

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-18 19:02

    Using DataTypeContexts reduces the number of programs you can write. If most of those illegal programs are nonsense, you might say it's worth the runtime cost associated with ghc passing in a type class dictionary that isn't used. For example, if we had

    data Ord k => MapDTC k a
    

    then @jefffrey's transf is rejected. But we should probably have transf _ = return (NonOrdA, 1) instead.

    In some sense the context is documentation that says "every Map must have ordered keys". If you look at all of the functions in Data.Map you'll get a similar conclusion "every useful Map has ordered keys". While you can create maps with unordered keys using

    mapKeysMonotonic :: (k1 -> k2) -> Map k1 a -> Map k2 a
    singleton :: k2 a -> Map k2 a
    

    But the moment you try to do anything useful with them, you'll wind up with No instance for Ord k2 somewhat later.

提交回复
热议问题