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
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.
Box
exampleAs 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:
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
Data.Map
caseData.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.