Advertisement
wavec022

pattern matching

Aug 21st, 2020 (edited)
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. Pattern Matching
  2.  
  3. def multAllPM(m: Int, List: List[Int]): List[Int] = list match {
  4. case Nil => Nil
  5. case head :: tail => m*head :: multAll(m, tail)
  6. }
  7.  
  8. def multAll(m: Int, list: List[Int]): List[Int] = {
  9. if(list == Nil) return Nil
  10. else return m*list.head :: multAll(m, list.tail)
  11. }
  12. test("multAll", multAll _, "m", "list")
  13.  
  14. =====
  15.  
  16. Some stuff pattern matching can do that if can't: what if we left out the base case by accident, the compiler would tell us that we forgot the empty case
  17. Or what if there was a typo
  18.  
  19. =====
  20.  
  21. Nested Patterns:
  22.  
  23. def everyOther(list: List[Int]): List[Int] = list match {
  24. case x :: _ :: rest => x :: everyOther(rest)
  25. case _ => list
  26. }
  27.  
  28. =====
  29.  
  30. Types of patterns:
  31.  
  32. _ matches anything
  33. x matches anything but can refer to it as x
  34. 0,1,"hello",true matches when it's exactly what the hardcoded value is
  35. Nil,None,Empty will only match that thing but it's for empty shit
  36.  
  37. def fact(n: Int): Int = n match {
  38. case 0 => 1
  39. case _ => n*fact(n-1)
  40. }
  41.  
  42. complex patterns-- (x,y,z) (Nil, "hello", 4)
  43. x :: xs
  44.  
  45. you can also use pattern matching in other stuff?
  46. val (x,y,z) = tup
  47. instead of val x = tup._1 etc
  48.  
  49. val Some(x) = opt
  50. val y :: ys = list
  51.  
  52. Some is an Option (can also be None)
  53.  
  54. var len = 0
  55. for (_ <- list) {
  56. len += 1
  57. }
  58. for (opt <- list) {
  59. if (opt != None)
  60. println(opt.get)
  61. }
  62.  
  63. sealed trait tree
  64. case object Empty extends Tree
  65. case class Node(left: Tree, item: Int, right: Tree) extends Tree
  66.  
  67. def size(tree: Tree): Int = tree match {
  68. case Empty => 0
  69. case Node(left,item,right)
  70. }
  71.  
  72. =====
  73.  
  74. def lookup(tree: Tree, find: Int): Boolean = tree match {
  75. case Empty => false
  76. case (left, item, right) => {
  77. if(item == find) true
  78. else if(item < find) lookup(left)
  79. else lookup(right)
  80. }
  81. }
  82.  
  83. =====
  84. =====
  85.  
  86. More Pattern Matching
  87.  
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement