我可以在 Haskell 中匹配数据构造函数通配符吗? [英] Can I match a data constructor wildcard in Haskell?
本文介绍了我可以在 Haskell 中匹配数据构造函数通配符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
data Foo = X (String, Int) | A String | B String | C String | D String -- ...
并已定义
f (X (s, _)) =s
f (A s) = s
f (B s) = s
f (C s) = s
f (D s) = s
-- ...
但更希望能够写出像
f (X (s, _)) =s
f (_ s) = s
但似乎没有办法做到这一点(我收到与 _
相关的解析错误").
But there seems to be no way to do this (I get a "parse error" associated with the _
).
有没有办法在 Haskell 中匹配数据构造函数通配符?
Is there a way to match a data constructor wildcard in Haskell?
推荐答案
不.但是你可以这样写:
Nope. But you can write this:
data Foo
= X { name :: String, age :: Int }
| A { name :: String }
| B { name :: String }
| C { name :: String }
| D { name :: String }
然后有 name :: Foo ->字符串
.你也可以考虑这个:
and then have name :: Foo -> String
. You could also consider this:
data Tag = A | B | C | D | X Int
data Foo = Tagged Tag String
f (Tagged _ s) = s
这篇关于我可以在 Haskell 中匹配数据构造函数通配符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文