Created
March 9, 2013 20:21
-
-
Save beans15/5125589 to your computer and use it in GitHub Desktop.
[scala] 同じリスト同士の直積
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
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