How to make specialized type classes for certain types, default implementation for the rest of types
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 开发者_如何学JAVAdo that?
It's not necessarily a safe or Haskell-y thing to do, but it is certainly possible, using OverlappingInstances
First, enable them:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
Write your casting class:
class Castable a b where
cast :: a -> Maybe b
cast _ = Nothing -- default implementation
An "optimized" instance:
instance Castable Int Bool where
cast 0 = Just False
cast _ = Just True
and finally, a general instance for all types:
instance Castable a b where
Example use:
main = do
print $ (cast (7 :: Int) :: Maybe Bool)
print $ (cast (7 :: Int) :: Maybe Integer)
Running this, the default is chosen when the types aren't specialized:
*Main> main
Just True
Nothing
精彩评论