Say I want to write a function for flattening lists, lists of lists, lists of lists of lists, etc. to just lists. I could write the following:
{-# LANGUAGE TypeFamilies #-}
class Flattenable a where
type Flattened a
flatten :: a -> Flattened a
instance NotFlattenable a => Flattenable [a] where
type Flattened [a] = [a]
flatten = id
instance Flattenable a => Flattenable [a] where
type Flattened [a] = Flattened a
flatten = concat . map flatten
Where NotFlattenable a
is some constraint restricting to those a
without an instance of Flattenable
. Is NotFlattenable
a legitimate constraint? How would I go about writing it? (Note that the absence of a NotFlattenable
constraint would make the two instances overlap)
No, this isn't possible since Haskell's type classes are always open: the compiler can never prove some instance does not exist, since somebody might still add it any time later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With