gpt4 book ai didi

跳过 Scala 模式匹配案例

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

感谢您提供的优秀示例,我试过了,它按我的预期工作。很高兴看到有人了解问题的本质。但是,我认为我应该用 Lift 标记问题,因为我正在使用 Lift 框架,这就是(仍然)发生这个问题的地方(尽管我仍然认为它可能与 scala 中的提取有关)。由于我不想在这里重现整个 Lift 设置,因为代码太多,我希望熟悉 Lift 的人能够理解我在这里所做的事情。我删除了更多变量,因此(对某些人而言)可能更容易看到问题:

lazy val dispatch: LiftRules.DispatchPF = {
// Explicitly setting guard to false to trigger the scenario
case req: Req if false => () => println("shouldn't match"); Empty
// This should match since previous case will never match
case Req(_, _, _) => () => println("should match"); Empty
// This is actually called...
case _ => () => println("shouldn't reach here"); Empty
}

和以前一样,如果我注释掉第一个案例,第二个案例将按预期匹配。

对于那些感兴趣的人,一个简单的解决方法是:
lazy val dispatch: LiftRules.DispatchPF = {
case req: Req => {
if (false) { // Obviously you put something more useful than false here...
() => println("shouldn't match"); Empty
} else req match {
// This matches
case Req(_, _, _) => () => println("should match"); Empty
// This is now never called
case other => () => println("shouldn't reach here"); Empty
}
}
}

原帖

我是 Scala 的新手,所以我可能在这里做错了,但我有一个似乎被跳过的模式匹配表达式。这是代码:
lazy val dispatch: LiftRules.DispatchPF = {
// Explicitly setting guard to false to trigger the scenario
case req: Req if false => () => Full(...)
// This should match since previous case will never match
case Req("api" :: "test" :: Nil, suffix, GetRequest) => () => Full(...)
// This is actually called...
case _ => () => println("not sure what's going on"); Empty
}

如果我取出第一个 case表达,一切都按预期进行。我很想认为这是一个错误( https://issues.scala-lang.org/browse/SI-2337 ),但有人知道解决方法吗?

最佳答案

至少,更改最后一行:

case other => () => { println("not sure what's going on " + other); Empty }

告诉我们它打印了什么

关于跳过 Scala 模式匹配案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6324379/

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