Scala 重複順列

Scala 重複順列

よく使うのですが、ワンライナーで書くことは出来ないでしょうか。現状は下記

program

object Main extends App {

  def duplicatePermutation[A](list: List[A], length: Int): List[List[A]] = {
    if (length == 1) {
      list.map(x => x :: Nil)
    } else {
      list.flatMap(x => duplicatePermutation(list, length-1).map(y => x :: y))
    }
  }

  val list = List(1, 2, 3)
  duplicatePermutation(list, 3).foreach(println)

}

terminal output

List(1, 1, 1)
List(1, 1, 2)
List(1, 1, 3)
List(1, 2, 1)
List(1, 2, 2)
List(1, 2, 3)
List(1, 3, 1)
List(1, 3, 2)
List(1, 3, 3)
List(2, 1, 1)
List(2, 1, 2)
List(2, 1, 3)
List(2, 2, 1)
List(2, 2, 2)
List(2, 2, 3)
List(2, 3, 1)
List(2, 3, 2)
List(2, 3, 3)
List(3, 1, 1)
List(3, 1, 2)
List(3, 1, 3)
List(3, 2, 1)
List(3, 2, 2)
List(3, 2, 3)
List(3, 3, 1)
List(3, 3, 2)
List(3, 3, 3)

参考

追記(181102)

implicit class RichList[A](val self: List[A]) {
  def duplicatePermutation(length: Int): List[List[A]] = {
    def proc(list: List[A], length: Int): List[List[A]] = {
      if (length == 1) {
        list.map(x => x :: Nil)
      } else {
        list.flatMap(x => proc(list, length-1).map(y => x :: y))
      }
    }
    proc(self, length)
  }
}

//

List(1, 2, 3).duplicatePermutation(3).foreach(println)