Skip to content

Instantly share code, notes, and snippets.

@dwins
Created July 22, 2010 15:52
Show Gist options
  • Select an option

  • Save dwins/486153 to your computer and use it in GitHub Desktop.

Select an option

Save dwins/486153 to your computer and use it in GitHub Desktop.
object Combine {
def linear[A](xs: Seq[A]): Seq[Seq[A]] =
xs match {
case Seq() => Seq(Seq())
case Seq(h, t @ _*) =>
linear(t) flatMap { ts => Seq(ts, h +: ts) }
}
def binary[A](xs: Seq[A]): Seq[Seq[A]] =
xs match {
case Seq() => Seq(Seq())
case Seq(x) => Seq(Seq(), Seq(x))
case xs =>
val (ls, rs) = xs.splitAt(xs.length / 2)
for (l <- binary(ls); r <- binary(rs)) yield l ++ r
}
}
Combine.linear(Seq.range(1, 5)) foreach println
println("-" * 10)
Combine.binary(Seq.range(1, 5)) foreach println
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment