gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:30:21 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com