目标是编写一个为特定值生成格雷码的函数。
目前我有这个:
def gray(i: Int): List[String] = {
if(i == 0) List("")
else {
val l = gray(i - 1)
(l map {"0" + _}) ::: (l map{"1" + _})
}
}
gray(3)
的输出: List(000, 001, 010, 011, 100, 101, 110, 111)
然后我尝试构建这个 List
用一个for循环。想象一下:
n = 2
,我将有:
def gray(i: Int): List[String] = {
(for{a <- 0 to 1
b <- 0 to 1} yield a+""+b).toList
}
n = 3
,我将有:
def gray(i: Int): List[String] = {
(for{a <- 0 to 1
b <- 0 to 1
c <- 0 to 1} yield a+""+b+""+c).toList
}
显然这没有考虑 i
,所以我想知道我们是否可以构建这样一个函数,它使用 i
构建自定义 for 循环表达式.
我的意思是构造:
如果i == 2
, 创建 2
循环变量并产生它们,如果i == 3
然后创建 3
并产生它们,等等。
有可能吗? (我是 Scala 的初学者)
最佳答案
def gray(n: Integer): List[List[Char]] = {
if (n == 0) List(List()) else
for {
c : List[Char] <- gray(n - 1)
i : Char <- List('0', '1')
} yield i :: c
} //> gray: (n: Integer)List[List[Char]]
val of0 = gray(0) //> of0 : List[List[Char]] = List(List())
val of1 = gray(1) //> of1 : List[List[Char]] = List(List(0), List(1))
val of2 = gray(2) //> of2 : List[List[Char]] = List(List(0, 0), List(1, 0), List(0, 1), List(1, 1))
...
关于scala - 构造自定义for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19787987/