I would like to have a type class of types that can possibly casted to other types when possible.
class Castable a b where
cast :: a -> Maybe b
cast _ = Nothing -- default implementation
Now the class would be implemented for some types and for all the others I would like to have default implementation.
How one can do that?
It’s not necessarily a safe or Haskell-y thing to do, but it is certainly possible, using OverlappingInstances
First, enable them:
Write your casting class:
An “optimized” instance:
and finally, a general instance for all types:
Example use:
Running this, the default is chosen when the types aren’t specialized: