haskell - Typeable 类型的“模式匹配”

标签 haskell syntax types dynamic-typing

例如,假设我们有以下数据结构:

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/

相关文章:

windows - 如何更改ghc的路径?

haskell - Haskell在记录字段中的保留关键字如何处理?

sql - 删除这些该死的 NULL

Python 在冒号后声明一个名称的类的奇怪方式

c# - 将字符串和字符放在一起的性能

json - 记录数据验证

Haskell 多重上下文 - 柯里化(Currying)?

java - 如何从循环生成的输出中删除最后一个星号?

go - 为什么下面这个 panic 例子是 golang 的类型错误?

c - 无效的目的*