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类型制作模式匹配的语法吗?
使用typeOf和守卫:
foo x
| tx == typeOf "str" = "string"
| tx == typeOf True = "bool"
| otherwise = "i dunno"
where tx = typeOf x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
257 次 |
| 最近记录: |