Haskell - 模式中守卫右侧使用通配符
可以说我有一段这样的代码:
test pattern
| pattern == (_,NOT (WIRE _)) = 1
| pattern == (_,AND (WIRE _) (WIRE _)) = 2
| otherwise = 0
我试图将它与几种可能性之一进行匹配,有些与一个(WIRE“”),有些与两个。我的实际输入如下,例如:(“p”,NOT(WIRE“x”))。我想要一个可以接受任何字母作为输入的模式(我所希望的_)并且失败得很惨(非法_)。在 haskell 中可以做到这一点吗?
Lets say i have a piece of code like this:
test pattern
| pattern == (_,NOT (WIRE _)) = 1
| pattern == (_,AND (WIRE _) (WIRE _)) = 2
| otherwise = 0
Where i am trying to match it against one of several possibilities, some with one (WIRE ""), some with two. I have actual input as follows e.g.: ("p",NOT (WIRE "x")). I would like to have a pattern that could accept any letter as input (what i was hoping for with the _) and am failing dismally (illegal _). Is it possible to do this in haskell?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,编辑后这更有意义。
==
比较值,但_
是模式。模式仅出现在以下语法上下文中:=
之前的内容”、在顶层或在where
块中或在let
表达式或命令中(以do
表示法);do
表示法或列表理解中<-
的左侧;case
表达式中->
的左侧;\
) 表达式中。(我希望我没有忘记任何!)在你的情况下,你可以通过简单地编写来实现你想要的
你可能会问“
pattern == (_, NOT (WIRE _))<的正确版本是什么/代码>”。好吧,你可以写:
OK, this makes a lot more sense after the edit.
==
compares values, but_
is a pattern. Patterns appear in only the following syntactic contexts:=
", at top level or inwhere
blocks or inlet
expressions or commands (indo
notation);<-
indo
notation or in a list comprehension;->
in acase
expression;\
) expressions.(I hope I haven't forgotten any!) In your case, you can achieve what you want by simply writing
You might ask what is the correct version of "
pattern == (_, NOT (WIRE _))
". Well, you can write:为什么你需要看守这个?我错过了什么吗?以下是我认为您正在寻找的合法 Haskell 代码。
Why do you need guards for this? Am I missing something? Below is the legal Haskell code I think you're looking for.