我写了一个用于测试的代码:
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))
}
我阅读了Scala第二版中的编程的“第15章:案例类和模式匹配”,但是我从未见过像这样使用case:
关键字,但是^^看起来像match。我知道部分函数并且可以通过这种方式使用case:... ^^ { case x ~ ":" ~ y => (x, y) }
不是match
object C extends App { def a(f: Int => Int) = { f(3) } a(x => x + 1) a { case x => x + 1 } }
但是它们都不同:
如何编写类似^^的自定义函数?你能写一个具体的例子吗?非常感谢!
我写了一段测试代码:类A扩展了JavaTokenParsers {def str:Parser [Any] = stringLiteral〜“:”〜stringLiteral ^^ {case x〜“:”〜y =>(x,y)} / / ...
只是语法糖。在scala中,可以使用任何将单个参数用作二进制运算符的方法。
如您所提到的,您可以使用带有case关键字的块来创建部分函数。