Advertisement
wavec022

more functional programming

Oct 20th, 2020 (edited)
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. more functional programming
  2.  
  3. map, filter, filternot, takeWhile, dropWhile, count, forall/exists
  4.  
  5. all except map take a predicate as a parameter -- function that returns a boolean
  6.  
  7. list.map(f).flatten // if a list of lists, concatenates into one list
  8. list.flatMap(f) // map followed by flatten but more efficient
  9.  
  10. list.foldRight(base)((currentElement, resultOfRecursiveCall) => glue logic)
  11.  
  12. list.foldRight(0)(_ + _) // returns sum
  13. list.foldRight(1)(_ * _) // returns product
  14. list.foldRight(List.empty[Int])(_.toString :: _)
  15.  
  16. prefixes(list)
  17.  
  18. prefixes(List(1,2,3)) = List(List(), List(1), List(1,2), List(1,2,3))
  19.  
  20. def prefixes(list: List[Int]): List[List[Int]] = {
  21. List.empty[Int] :: list.foldRight(List.empty[Int])((x,y) => List
  22. }
  23.  
  24. (1,2,3)
  25. 1 D 2,3
  26. 1 C 2,3 1; 1,2; 1,2,3
  27.  
  28. =====
  29.  
  30. // The solution
  31.  
  32. def prefixes(list: List[Int]): List[List[Int]] = {
  33. list.foldRight(List(List.empty[A]))((x,lol) => List.empty[A] :: lol.map(x :: _))
  34. }
  35.  
  36. (1,2,3)
  37. x 1 (2,3)
  38. ((), (2), (2,3)) lol
  39. 1 :: all of that shit
  40. ((1), (1,2), (1,2,3))
  41. so it's just map(x :: _)
  42. and then work in the empty list at the front
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement