Advertisement
wavec022

Recursion Notes

Jan 27th, 2020
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. Recursion notes
  2.  
  3. Divide conquer glue
  4.  
  5. ALWAYS USE BASE CASE
  6.  
  7. def sum(list: List[Int]): Int = {
  8. if(list.isEmpty) { 0 }
  9. else { list.head + sum(list.tail) }
  10. }
  11.  
  12. list(2,4,6,8,10)
  13. 2 (list.head) DIVIDE (4,6,8,10) (list.head)
  14. CONQUER sum(list.tail) (28)
  15. GLUE
  16. (+)
  17.  
  18. list.head + sum(list.tail)
  19.  
  20. 30
  21.  
  22. =====
  23.  
  24. def length(list: List[Int]): Int = {
  25.  
  26. }
  27.  
  28. list(2,4,6,8,10)
  29.  
  30. 2 DIVIDE (4,6,8,10)
  31. CONQ (4) length(list.tail)
  32. GLUE
  33. 1 + 4 1 + length(list.tail)
  34.  
  35. ======
  36.  
  37. def max(list: List[Int]): Int = {
  38.  
  39. }
  40.  
  41. list(2,4,6,6,8,3)
  42.  
  43. 2 DIVIDE (4,6,6,8,3)
  44. CONQ (8) max(list.tail)
  45. GLUE
  46. 2 > 10 list.head > max(list.tail)
  47. 8
  48.  
  49. =======================
  50. -----------------------
  51. =======================
  52.  
  53. Maps-- key value pairs
  54.  
  55. "a set is a set is a set"
  56.  
  57. val s = Set(1,3,5)
  58. this is an immutable set
  59.  
  60. s(3)-- s contains 3
  61.  
  62. s + 7: adds 7 to set
  63.  
  64. ===
  65.  
  66. val myMap = Map("Cat" -> 3, "dog" -> 5)
  67. myMap("dog")
  68. myMap.contains("fox")
  69.  
  70. ===
  71.  
  72. there are also Options
  73.  
  74. myMap.get("Cat") => Option[Int] = Some(3)
  75.  
  76. myMap.getOrElse("fox",0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement