Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Last active December 28, 2015 04:19
Show Gist options
  • Save tpolecat/7441358 to your computer and use it in GitHub Desktop.
Save tpolecat/7441358 to your computer and use it in GitHub Desktop.
scala> :pa
// Entering paste mode (ctrl-D to finish)
def subsets[A](as: List[A]): List[List[A]] = {
def sub0(accum: List[List[A]], as: List[A]): List[List[A]] =
as match {
case Nil => accum
case a :: as => sub0(accum ++ accum.map(a :: _), as)
}
sub0(List(Nil), as)
}
// Exiting paste mode, now interpreting.
subsets: [A](as: List[A])List[List[A]]
scala> subsets(List(1, 2, 3, 4, 5)).filter(_.sum < 8)
res9: List[List[Int]] = List(List(), List(1), List(2), List(2, 1), List(3), List(3, 1), List(3, 2), List(3, 2, 1), List(4), List(4, 1), List(4, 2), List(4, 2, 1), List(4, 3), List(5), List(5, 1), List(5, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment