help rewriting in functional style

后端 未结 5 2128
再見小時候
再見小時候 2021-02-10 10:46

I\'m learning Scala as my first functional-ish language. As one of the problems, I was trying to find a functional way of generating the sequence S up to n places. S is defined

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-10 11:27

    The following code produces exactly the same sequence as yours:

    val seq = Stream.from(1)
            .flatMap(Stream.fill(2)(_))
            .zipWithIndex
            .flatMap(p => Stream.fill(p._1)(p._2))
            .tail
    

    However, if you want to produce the Golomb sequence (that complies with the definition, but differs from your sample code result), you may use the following:

    val seq = 1 #:: a(2)
    def a(n: Int): Stream[Int] = (1 + seq(n - seq(seq(n - 2) - 1) - 1)) #:: a(n + 1)
    

    You may check my article for more examples of how to deal with number sequences in functional style.

提交回复
热议问题