scala - 构造自定义for循环

标签 scala for-loop

目标是编写一个为特定值生成格雷码的函数。

目前我有这个:

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/

相关文章:

c# - for循环背后的逻辑

javascript - 我将使用什么函数来完成我的程序? For循环还有什么?

java - 将嵌套循环转换为 Java 8 流

sql - 如何防止sql中in子句出现空列表错误?

scala - "could not find implicit value for parameter rs: spray.routing.RoutingSettings"的原因

Scala:线程安全的循环迭代器

scala - 如何使用 Scala 和 Mockito 测试异步副作用

c - 如何使用 Java/Scala 在内存 G-wan 中保存数据结构

python - 在Python中循环和计算json响应

linux - 在管道 awk 输出上打印循环输入文件名