gpt4 book ai didi

Scala:如何在没有匹配关键字的情况下使用 case 关键字?

转载 作者:行者123 更新时间:2023-12-03 17:05:22 27 4
gpt4 key购买 nike

我写了一段代码进行测试:

class A extends JavaTokenParsers {
def str: Parser[Any] = stringLiteral ~ ":" ~ stringLiteral ^^
{ case x ~ ":" ~ y => (x, y) } //how to use case keyword like this?
}

object B extends A with App{
val s = """
"name": "John"
"""
println(parseAll(str, s))
}

我阅读了 的“第 15 章:案例类和模式匹配” Scala编程第二版 ,但我从未见过 案例像这样使用:
... ^^ { case x ~ ":" ~ y => (x, y) } 

不是 匹配 关键字,但 ^^ 看起来像 匹配 .我知道 偏函数我可以使用 案例通过这种方式:
object C extends App {
def a(f: Int => Int) = {
f(3)
}
a(x => x + 1)
a { case x => x + 1 }
}

但它们都不同:
  • ^^ 函数如 匹配 , 可以使用 之前的内容^^ 后面的匹配内容案例
  • 案例在 ^^ 函数中可以使用函数(如 ~ )

  • 如何编写像^^这样的自定义函数?你能写一个具体的例子吗?非常感谢!

    最佳答案

    这只是语法糖。在 scala 中,您可以使用任何将单个参数作为二元运算符的方法。

    例子:

    class Foo(x: String) {
    def ^^(pf: PartialFunction[String, Int]): Option[Int] =
    if (pf.isDefinedAt(x)) Some(pf(x)) else None
    }

    val foo = new Foo("bar")
    foo ^^ {
    case "baz" => 41
    case "bar" => 42
    }

    // result: Some(42)

    关于Scala:如何在没有匹配关键字的情况下使用 case 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34610126/

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