Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //example of 2 levels of recursion
- def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
- ls match {
- case Nil => Nil
- case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
- }
- def combinations[A](n: Int, ls: List[A]): List[List[A]] =
- if (n == 0) List(Nil)
- else flatMapSublists(ls) { sl =>
- combinations(n - 1, sl.tail) map {sl.head :: _}
- }
- //note val f = (s:Int) => List(Nil).map(s :: _)
- equates to List(List(s))
- // answer should be List(List(1,2),List(1,3),List(1,4),List(2,3),List(2,4),List(3,4))
- // for input of combinations(2,List(1,2,3,4))
- //stage 1 - starting from inside combinations
- FM(List(1,2,3,4) { s1 => C(1, List(2,3,4) map {s1.head :: _} }
- //stage 2
- FM(List(1,2,3,4) { s1 => FM(List(2,3,4) { s1 => C(0,List(3,4)) map {s1.head :: _}} map {s1.head :: _}}
- //stage 3
- FM(List(1,2,3,4) { s1 => FM(List(2,3,4) { s1 => List(Nil) map {s1.head :: _}} map {s1.head :: _}}
- //stage 4
- FM(List(1,2,3,4) { s1 => List(List(2),List(3),List(4)) map {s1.head :: _}}
- note up to stage 4 we have only expanded the inner recursion. that is starting from FM(List(1,2,3,4) { s1 =>
- the result of stage 4 would be List(List(1,2),List(1,3),List(1,4)). Remember though the outer FM is also recursive as shown in stage 5
- //stage 5
- f(List(1,2,3,4) ::: f(List(2,3,4)) ::: f(List(3,4)) ::: f(List(4))
- we have already expanded out the first term, the function (f) is inside the braces of stage 4, the second f term of stage 5 will have
- a similar pattern. its function will be
- {s1 => List(List(3),List(4)) map {s1.head :: _ }}
- this will generate the List(List(2,3), List(2,4)) terms
- similarly the third term of stage 5 f function is {s1 => List(List(4)) map {s1.head :: _}}
- this will generate the term List(List(3,4))
- the last case f(List(4)) is as follows:
- FM(List(4) { s1 => C(1,List()) map {s1.head :: _}}
- ths expands to
- FM(List(4) { s1 => Nil}
- hence this term is dropped.
- must admit i think 2 levels of recursion (a function that has 2 recursive functions) seems confusing, maybe it eventually becomes as simple
- as a function that just calls itself (one level of recursion) once you are familiar with it ???
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement