例如,假设我们有以下数据结构:
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 类型的模式匹配制定语法吗?
最佳答案
使用 typeOf
和守卫:
foo x
| tx == typeOf "str" = "string"
| tx == typeOf True = "bool"
| otherwise = "i dunno"
where tx = typeOf x
关于haskell - Typeable 类型的“模式匹配”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5885914/