可键入类型的"模式匹配"

3 syntax haskell types dynamic-typing

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

data Foo = Bool Bool | Int Int | Double Double
Run Code Online (Sandbox Code Playgroud)

现在,有更简单的方法来做到这一点:

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)
Run Code Online (Sandbox Code Playgroud)

有人想过为Typeable类型制作模式匹配的语法吗?

scl*_*clv 6

使用typeOf和守卫:

foo x
    | tx == typeOf "str" = "string"
    | tx == typeOf True  = "bool"
    | otherwise          = "i dunno"
  where tx = typeOf x
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是一个很好的方法.一个小问题是,在OverloadedStrings存在的情况下,typeOf"str"将无法正常工作,而现在这种情况变得越来越普遍. (2认同)