开发者

Make a recursive Stream from just 1 element?

I've made a Stream for Gray Codes using recursion as follows:

val gray: Stream[List[String]] = {
 List("") #:: List("0", "1") #:: gray.tail.map {gnext} 
}

where

val gnext = (i:List[String]) => i.map {"0" + _} ::: i.reverse.map {"1" + _}

so that, for example

scala> gray(2)
res17: List[String] = List(00, 01, 11, 10)

I don't really need the List("0", "1") in the definition, because it can be produced from element 0:

scala> gnext(List(""))
res18: List[java.lang.String] = List(0, 1)

So is there a way / pattern that can be 开发者_如何学运维used to produce a Stream from just the first element?


val gray: Stream[List[String]] = List("") #:: gray.map {gnext}

Or, alternatively,

val gray = Stream.iterate(List(""))(gnext)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜