Skip to content

Instantly share code, notes, and snippets.

@duarten
Created April 22, 2013 09:32
Show Gist options
  • Save duarten/5433567 to your computer and use it in GitHub Desktop.
Save duarten/5433567 to your computer and use it in GitHub Desktop.
For a given list, returns all the possible partitions of that list.
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