Why constraints on data are a bad thing?

前端 未结 3 1030
深忆病人
深忆病人 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 18:52

    Constraints

    The problem is that constraints are not a property of the data type, but of the algorithm/function that operates on them. Different functions might need different and unique constraints.

    A Box example

    As an example, let's assume we want to create a container called Box which contains only 2 values.

    data Box a = Box a a
    

    We want it to:

    • be showable
    • allow the sorting of the two elements via sort

    Does it make sense to apply the constraint of both Ord and Show on the data type? No, because the data type in itself could be only shown or only sorted and therefore the constraints are related to its use, not it's definition.

    instance (Show a) => Show (Box a) where
        show (Box a b) = concat ["'", show a, ", ", show b, "'"]
    
    instance (Ord a) => Ord (Box a) where
        compare (Box a b) (Box c d) =
            let ca = compare a c
                cb = compare b d
            in if ca /= EQ then ca else cb
    

    The Data.Map case

    Data.Map's Ord constraints on the type is really needed only when we have > 1 elements in the container. Otherwise the container is usable even without an Ord key. For example, this algorithm:

    transf :: Map NonOrd Int -> Map NonOrd Int
    transf x = 
        if Map.null x
            then Map.singleton NonOrdA 1
            else x
    

    Live demo

    works just fine without the Ord constraint and always produce a non empty map.

提交回复
热议问题