有没有办法定义这样的函数:
f :: (C a, C b) => a -> Maybe b
Run Code Online (Sandbox Code Playgroud)
这样:
f = Just
Run Code Online (Sandbox Code Playgroud)
当type a= b,和
f _ = Nothing
Run Code Online (Sandbox Code Playgroud)
当键入a/ = b?
注意:
C,但我很确定它是必要的(特别是如果我想避免重叠实例).Equal a b会使这个问题变得微不足道但是它需要n^2我想要避免的实例.http://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Typeable.html#v:cast
cast :: (Typeable a, Typeable b) => a -> Maybe b
Run Code Online (Sandbox Code Playgroud)
函数转换可以是"类型转换系统,如面向对象语言"的一部分.细菌和真菌就是生命.他们可以升到生活.生命可能会转向细菌或真菌.
{-# 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 ())
Run Code Online (Sandbox Code Playgroud)
此技术扩展到类型层次结构系统.全寿命模块就在这里. 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
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |