Haskell - 模式中守卫右侧使用通配符

发布于 2024-09-24 17:21:47 字数 299 浏览 11 评论 0原文

可以说我有一段这样的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

塔塔猫 2024-10-01 17:21:47

好的,编辑后这更有意义。

== 比较,但_模式。模式仅出现在以下语法上下文中:

  • 在(模式)绑定的左侧,即“= 之前的内容”、在顶层或在 where 块中或在 let 表达式或命令中(以 do 表示法);
  • do 表示法或列表理解中 <- 的左侧;
  • 位于 case 表达式中 -> 的左侧;
  • 作为函数的形式参数,无论是在函数绑定还是 lambda (\) 表达式中。

(我希望我没有忘记任何!)在你的情况下,你可以通过简单地编写来实现你想要的

test (_, NOT (WIRE _)) = 1
test (_, AND (WIRE _) (WIRE _)) = 2
test _ = 0

你可能会问“pattern == (_, NOT (WIRE _))<的正确版本是什么/代码>”。好吧,你可以写:

case pattern of
  (_, NOT (WIRE _)) -> True
  _ -> False

OK, this makes a lot more sense after the edit.

== compares values, but _ is a pattern. Patterns appear in only the following syntactic contexts:

  • on the left hand side of a (pattern) binding, i.e. "what's before =", at top level or in where blocks or in let expressions or commands (in do notation);
  • to the left of <- in do notation or in a list comprehension;
  • to the left of -> in a case expression;
  • as the formal arguments of functions, either in function bindings or lambda (\) expressions.

(I hope I haven't forgotten any!) In your case, you can achieve what you want by simply writing

test (_, NOT (WIRE _)) = 1
test (_, AND (WIRE _) (WIRE _)) = 2
test _ = 0

You might ask what is the correct version of "pattern == (_, NOT (WIRE _))". Well, you can write:

case pattern of
  (_, NOT (WIRE _)) -> True
  _ -> False
﹉夏雨初晴づ 2024-10-01 17:21:47

为什么你需要看守这个?我错过了什么吗?以下是我认为您正在寻找的合法 Haskell 代码。

test (_,NOT (WIRE _)) = 1     
test (_,AND (WIRE _) (WIRE _)) = 2
test _ = 0

Why do you need guards for this? Am I missing something? Below is the legal Haskell code I think you're looking for.

test (_,NOT (WIRE _)) = 1     
test (_,AND (WIRE _) (WIRE _)) = 2
test _ = 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文