例如,假设我们有以下数据结构:
data Foo = Bool Bool | Int Int | Double Double
现在,有更简单的方法吗?
foo :: Typeable a => a -> Foo
foo x = maybe (error "i dunno") id $
liftM Bool (cast x) `mplus`
liftM Int (cast x) `mplus`
liftM Double (cast x)
有人想过在 Typeable 类型上为模式匹配制作语法吗?
答案 0 :(得分:6)
使用typeOf
和警卫:
foo x
| tx == typeOf "str" = "string"
| tx == typeOf True = "bool"
| otherwise = "i dunno"
where tx = typeOf x
答案 1 :(得分:4)
你可以在这里使用视图模式,它们是非常方便的扩展。
{-# LANGUAGE ViewPatterns #-}
import Data.Data
data Foo = Bool Bool | Int Int | Double Double
deriving (Show)
foo :: Typeable a => a -> Foo
foo (cast -> Just x) = Int x
foo (cast -> Just x) = Bool x
foo (cast -> Just x) = Double x
foo _ = error "i dunno"
结果:
*Main> :l foo_typeable.hs [1 of 1] Compiling Main ( foo_typeable.hs, interpreted ) Ok, modules loaded: Main. *Main> foo "123" *** Exception: i dunno *Main> foo 1 *** Exception: i dunno *Main> foo (1 :: Int) Int 1 *Main> foo (1 :: Integer) *** Exception: i dunno *Main> foo (1 :: Double) Double 1.0
答案 2 :(得分:3)
此版本不限于Bool
,Int
或Double
,而String
则为[Char]
。
foo :: Typeable a => a -> String
foo = show . typeOf