Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- more functional programming
- map, filter, filternot, takeWhile, dropWhile, count, forall/exists
- all except map take a predicate as a parameter -- function that returns a boolean
- list.map(f).flatten // if a list of lists, concatenates into one list
- list.flatMap(f) // map followed by flatten but more efficient
- list.foldRight(base)((currentElement, resultOfRecursiveCall) => glue logic)
- list.foldRight(0)(_ + _) // returns sum
- list.foldRight(1)(_ * _) // returns product
- list.foldRight(List.empty[Int])(_.toString :: _)
- prefixes(list)
- prefixes(List(1,2,3)) = List(List(), List(1), List(1,2), List(1,2,3))
- def prefixes(list: List[Int]): List[List[Int]] = {
- List.empty[Int] :: list.foldRight(List.empty[Int])((x,y) => List
- }
- (1,2,3)
- 1 D 2,3
- 1 C 2,3 1; 1,2; 1,2,3
- =====
- // The solution
- def prefixes(list: List[Int]): List[List[Int]] = {
- list.foldRight(List(List.empty[A]))((x,lol) => List.empty[A] :: lol.map(x :: _))
- }
- (1,2,3)
- x 1 (2,3)
- ((), (2), (2,3)) lol
- 1 :: all of that shit
- ((1), (1,2), (1,2,3))
- so it's just map(x :: _)
- and then work in the empty list at the front
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement