Có cú pháp nào trong Scala cho phép trình giải nén có một đối số tùy chỉnh không? Ví dụ này là một chút contrived. Giả sử tôi có một cây tìm kiếm nhị phân trên các số nguyên và tôi muốn khớp trên nút hiện tại nếu giá trị của nó có thể chia hết cho một số giá trị tùy chỉnh.Scala Extractor với đối số
Sử dụng F # mô hình hoạt động, tôi có thể làm như sau:
type Tree =
| Node of int * Tree * Tree
| Empty
let (|NodeDivisibleBy|_|) x t =
match t with
| Empty -> None
| Node(y, l, r) -> if y % x = 0 then Some((l, r)) else None
let doit = function
| NodeDivisibleBy(2)(l, r) -> printfn "Matched two: %A %A" l r
| NodeDivisibleBy(3)(l, r) -> printfn "Matched three: %A %A" l r
| _ -> printfn "Nada"
[<EntryPoint>]
let main args =
let t10 = Node(10, Node(1, Empty, Empty), Empty)
let t15 = Node(15, Node(1, Empty, Empty), Empty)
doit t10
doit t15
0
Trong Scala, tôi có thể làm điều gì đó tương tự, nhưng không hoàn toàn những gì tôi muốn:
sealed trait Tree
case object Empty extends Tree
case class Node(v: Int, l: Tree, r: Tree) extends Tree
object NodeDivisibleBy {
def apply(x: Int) = new {
def unapply(t: Tree) = t match {
case Empty => None
case Node(y, l, r) => if (y % x == 0) Some((l, r)) else None
}
}
}
def doit(t: Tree) {
// I would prefer to not need these two lines.
val NodeDivisibleBy2 = NodeDivisibleBy(2)
val NodeDivisibleBy3 = NodeDivisibleBy(3)
t match {
case NodeDivisibleBy2(l, r) => println("Matched two: " + l + " " + r)
case NodeDivisibleBy3(l, r) => println("Matched three: " + l + " " + r)
case _ => println("Nada")
}
}
val t10 = Node(10, Node(1, Empty, Empty), Empty)
val t15 = Node(15, Node(1, Empty, Empty), Empty)
doit(t10)
doit(t15)
Nó sẽ là tuyệt vời nếu Tôi có thể làm:
case NodeDivisibleBy(2)(l, r) => println("Matched two: " + l + " " + r)
case NodeDivisibleBy(3)(l, r) => println("Matched three: " + l + " " + r)
nhưng đây là lỗi thời gian biên dịch: '=>' mong đợi nhưng '(' tìm thấy.
Suy nghĩ?
Đây là Scala 2.10 phải không? –