It is not necessarily safe or Haskell-y, but it is certainly possible using OverlappingInstances
Turn them on first:
{-
Write a casting class:
class Castable ab where cast :: a -> Maybe b cast _ = Nothing -- default implementation
"Optimized" instance:
instance Castable Int Bool where cast 0 = Just False cast _ = Just True
and finally, a common instance for all types:
instance Castable ab where
Usage example:
main = do print $ (cast (7 :: Int) :: Maybe Bool) print $ (cast (7 :: Int) :: Maybe Integer)
By doing this, a default value is selected if the types are not specialized:
*Main> main Just True Nothing
source share