Created
April 22, 2013 09:32
-
-
Save duarten/5433567 to your computer and use it in GitHub Desktop.
For a given list, returns all the possible partitions of that list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Partition[A] = List[List[A]] | |
def partitions[A](xs: List[A]): List[Partition[A]] = l match { | |
case Nil => Nil | |
case h :: Nil => List(List(List(h))) | |
case h :: t => | |
val ps = partitions(t) | |
ps.map(List(h) :: _) ::: ps.flatMap(interpolate(h, _)) | |
} | |
private def interpolate[A](item: A, partition: Partition[A]): List[Partition[A]] = interpolateAcc(item, partition, Nil) | |
private def interpolateAcc[A](item: A, partition: Partition[A], prev: Partition[A]): List[Partition[A]] = partition match { | |
case Nil => Nil | |
case h :: t => (prev ::: ((item :: h) :: t)) :: interpolateAcc(item, t, prev :+ h) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment