有没有办法定义这样的函数:
$('.cameraContent',fakeHover).fadeOut(600);
这样:
f :: (C a, C b) => a -> Maybe b
类型f = Just
= a
和
b
类型f _ = Nothing
/ = a
?
请注意:
b
,但我非常确定它是必要的(特别是如果我想避免重叠实例)。C
会使这个问题变得微不足道,但它需要{I}个实例,我想避免这些实例。 答案 0 :(得分:9)
http://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Typeable.html#v:cast
cast :: (Typeable a, Typeable b) => a -> Maybe b
函数转换可以是“类型转换系统,如面向对象语言”的一部分。细菌和真菌就是生命。他们可以升到生活。而生命可能会被转向细菌或真菌。
{-# 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 ())
此技术扩展到类型层次结构系统。全寿命模块就在这里。 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