I tried to look for some algorithms to find all of the sub lists of a given list and this is what I found:
The only sublist of the empty list is the empty list. The sublists of x:xs (ie the list with the head x and the tail xs) are all of the sublists of xs as well as each of the sublists of xs with x prepended to them.
taken from Sublists of a list using list comprehension
Here is what I implemented:
def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match{
case List() => List()
case x::xs => combinations(xs) ::: combinations(x :: xs)
}
This function gives a stack overflow error as I expected however in the example from that question it worked for him. It might've been that I misunderstood the principle he explained? How could I tackle such a problem using recursion? Where was my mistake here?
Where can I look for such an algorithm?
This would be the algorithm according to your stated definition.
For the empty List, return a List with an empty List.
For the other case, use recursion to get all combinations from the tail
and then additionally combine the head
with each element from the result ( tailComb
). ( tailComb.map(sub => x :: sub)
).
def combinations[A](list: List[A]): List[List[A]] = list match {
case Nil => List(List.empty[A])
case x::xs => {
val tailComb = combinations(xs)
tailComb ::: tailComb.map(sub => x :: sub)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.