Type equality function

Is there any way to define such a function:

f :: (C a, C b) => a -> Maybe b

Thus:

f = Just

when type a= band

f _ = Nothing

when is type a/ = b?

Note that:

  • I do not want to use overlapping instances.
  • I would prefer not to have a class constraint C, but I'm sure this is necessary (especially if I want to avoid duplicate instances).
  • I want to define only one instance for each type that I want to compare in this scheme, class definition Equal a bmakes this problem trivial, but this requires instances n^2that I want to avoid.
+6
source share
1 answer

Just this

http://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Typeable.html#v:cast

cast :: (Typeable a, Typeable b) => a -> Maybe b

cast " , - ". - . . .

{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable #-}

import Data.Typeable
import Data.Maybe

data SomeLife = forall l . Life l => SomeLife l
        deriving Typeable

instance Show SomeLife where
        show (SomeLife l) = "SomeLife " ++ show l

class (Typeable l, Show l) => Life l where
        toLife :: l -> SomeLife
        fromLife :: SomeLife -> Maybe l

        toLife = SomeLife
        fromLife (SomeLife l) = cast l

instance Life SomeLife where
        toLife = id
        fromLife = Just

data Bacteria = Bacteria deriving (Typeable, Show)

instance Life Bacteria

data Fungus = Fungus deriving (Typeable, Show)

instance Life Fungus

castLife :: (Life l1, Life l2) => l1 -> Maybe l2
castLife = fromLife . toLife

filterLife :: (Life l1, Life l2) => [l1] -> [l2]
filterLife = catMaybes . map castLife

withLifeIO :: (Life l1, Life l2) => l1 -> (l2 -> IO ()) -> IO ()
withLifeIO l f = maybe (return ()) f $ castLife l

withYourFavoriteLife :: Life l => (l -> IO ()) -> IO ()
withYourFavoriteLife act = do
        withLifeIO Bacteria act
        withLifeIO Fungus act

main :: IO ()
main = do
        let     sls :: Life l => [l]
                sls = filterLife [
                        SomeLife Bacteria,
                        SomeLife Fungus,
                        SomeLife Fungus ]
        print (sls :: [SomeLife])
        print (sls :: [Bacteria])
        print (sls :: [Fungus])
        withYourFavoriteLife (print :: SomeLife -> IO ())
        withYourFavoriteLife (print :: Bacteria -> IO ())
        withYourFavoriteLife (print :: Fungus -> IO ())

. Whole Life . https://github.com/YoshikuniJujo/test_haskell/blob/master/features/existential_quantifications/type_hierarchy/Life.hs

. https://hackage.haskell.org/package/base-4.9.1.0/docs/Control-Exception.html

+9

All Articles