Witch is a library of mine that allows you to confidently convert between values of various types. I’m happy to announce version 1.2.3.1, which adds the ability to define generic conversions between types that are structurally similar.
https://hackage.haskell.org/package/witch-1.2.3.1/docs/Witch-Generic.html
In short, you can now do this:
ghci> data Toggle = Off | On deriving (Generic, Show)
ghci> deriving via Generically Toggle instance From Bool Toggle
ghci> into @Toggle True
On
Witch does this by converting the source type (s
) into its generic representation (Rep s
), converting that into the generic representation of the target type (Rep t
), and then converting that into the target type (t
). As long as the generic representations are the same, the conversion will work.
Witch also handles converting any types inside those types, provided that an appropriate From
instance exists. For example you can do this:
ghci> data Pair a b = MkPair a b deriving (Generic, Show)
ghci> deriving via Generically (Pair c d) instance (From a c, From b d) => From (a, b) (Pair c d)
ghci> into @(Pair Integer Float) (1 :: Int, 2.3 :: Double)
MkPair 1 2.3
In addition to converting (,)
into Pair
, it also converts Int
into Integer
and Double
into Float
. That’s because Witch provides instance From Int Integer
and instance From Double Float
.
Thanks for reading! I hope you find this useful (or at least interesting).