我可以在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 -> String
.您还可以考虑以下问题:
and then have name :: Foo -> String
. You could also consider this:
data Tag = A | B | C | D
data Foo = X String Int | Tagged Tag String
f (X s _) = s
f (Tagged _ s) = s
这篇关于我可以在Haskell中匹配数据构造函数通配符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文