## 2016年7月10日 星期日

### [Scala 小學堂] Scala Gossic : 繼續深入 - 模式比對 (變數綁定、模式防護)

Source From Here

1. def what(list: List[Int]) = list match {
2.     case List(2, _*)   => list.tail
3.     case List(3, _*)   => list.tail
4.     case _             => Nil
5. }
6.
7. println(what(List(2345)))   // List(3, 4, 5)
8. println(what(List(3456)))   // List(4, 5, 6)
9. println(what(List(1345)))   // List()

1. def what(list: List[Int]) = list match {
2.     case List(2, tail @ _*)   => tail
3.     case List(3, tail @ _*)   => tail
4.     case _                    => Nil
5. }
6.
7. println(what(List(2345)))   // List(3, 4, 5)
8. println(what(List(3456)))   // List(4, 5, 6)
9. println(what(List(1345)))   // List()

1. case class Point(x: Int, y: Int)
2. case class Circle(p: Point, r: Int)
3. case class Cylinder(c: Circle, h: Int)
4.
5. def what(c: Cylinder) = c match {
6.     case Cylinder(circle @ Circle(Point(00), _), _) => circle
7.     case _                                            => null
8. }
9.
10. val cy1 = Cylinder(Circle(Point(00), 10), 10)
11. val cy2 = Cylinder(Circle(Point(00), 20), 20)
12. val cy3 = Cylinder(Circle(Point(11), 20), 20)
13. println(what(cy1))  // Circle(Point(0,0),10)
14. println(what(cy2))  // Circle(Point(0,0),20)
15. println(what(cy3))  // null

1. case class Point(x: Int, y: Int)
2. case class Circle(p: Point, r: Int)
3. case class Cylinder(c: Circle, h: Int)
4.
5. def what(c: Cylinder) = c match {
6.     case Cylinder(Circle(Point(00), _), _) => c.c
7.     case _                                   => null
8. }
9.
10. val cy1 = Cylinder(Circle(Point(00), 10), 10)
11. val cy2 = Cylinder(Circle(Point(00), 20), 20)
12. val cy3 = Cylinder(Circle(Point(11), 20), 20)
13. println(what(cy1))  // Circle(Point(0,0),10)
14. println(what(cy2))  // Circle(Point(0,0),20)
15. println(what(cy3))  // null

1. case class Point(x: Int, y: Int)
2. case class Circle(p: Point, r: Int)
3.
4. def what(c: Circle) = c match {
5.     case Circle(Point(x, y), r) if x == y => r
6.     case _                                => c
7. }
8.
9. println(what(Circle(Point(11), 10)))   // 10
10. println(what(Circle(Point(22), 20)))   // 20
11. println(what(Circle(Point(31), 10)))   // Circle(Point(3,1),10)
12. println(what(Circle(Point(44), 30)))   // 30

1. case class Point(x: Int, y: Int)
2. case class Circle(p: Point, r: Int)
3.
4. def what(c: Circle) = c match {
5.     case Circle(Point(x, y), r) => if(x == y) r else c
6. }
7.
8. println(what(Circle(Point(11), 10)))   // 10
9. println(what(Circle(Point(22), 20)))   // 20
10. println(what(Circle(Point(31), 10)))   // Circle(Point(3,1),10)
11. println(what(Circle(Point(44), 30)))   // 30

## 關於我自己

Where there is a will, there is a way!