Skip to content

Instantly share code, notes, and snippets.

@beans15
Created March 9, 2013 20:21
Show Gist options
  • Save beans15/5125589 to your computer and use it in GitHub Desktop.
Save beans15/5125589 to your computer and use it in GitHub Desktop.
[scala] 同じリスト同士の直積
def product[A](list: Seq[A], length: Int): Iterator[Seq[A]] = {
@tailrec
def _product(list: Stream[A], length: Int,
accum: Stream[Seq[A]]): Stream[Seq[A]] = {
length match {
case 0 => accum
case _ =>
_product(list, length - 1,
list map {
x => (x, accum)
} flatMap {
case (c, ls) => ls.map(y => x +: y)
})
}
}
val init = list.toStream
_product(init, length - 1, init.map(_.toString)).toIterator
}
// > println(product(List(1, 2), 2).toList)
// List(List(1, 1), List(1, 2), List(2, 1), List(2, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment