目标是编写一个为特定值生成格雷码的函数.
目前我有这个:
def gray(i: Int): List[String] = {
if(i == 0) List("")
else {
val l = gray(i - 1)
(l map {"0" + _}) ::: (l map{"1" + _})
}
}
Run Code Online (Sandbox Code Playgroud)
输出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
}
Run Code Online (Sandbox Code Playgroud)
因为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
}
Run Code Online (Sandbox Code Playgroud)
显然这没有考虑到i,所以我想知道我们是否可以构建这样一个函数,使用构造循环表达式的自定义i.
通过构造我的意思是:
如果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))
...
Run Code Online (Sandbox Code Playgroud)