帮助重写功能风格 [英] help rewriting in functional style

查看:106
本文介绍了帮助重写功能风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Scala作为我的第一个功能语言。作为其中一个问题,我试图找到一个生成序列S到达n个位置的函数式方法。 S被定义为使得S(1)= 1,并且S(x)=序列中出现的次数x。 (我不记得这是什么,但是我之前在编程书籍中已经看到它。)

实际上,序列看起来像这样:

  S = 1,2,3,2,4,4,5,5,5,6,6,6 ,6,7,7,7,7 ... 

我可以很容易地生成这个序列Scala使用像这样的命令式样:

  def genSequence(numItems:Int)= {
require(numItems> 0,numItems必须> = 1)
var list:List [Int] = List(1)
var seq_no = 2
var no = 2
var no_nos = 0
var num_made = 1

while(num_made< numItems){
if(no_nos< seq_no){
list = list:+ no
no_nos + = 1
num_made + = 1
} else if(no%2 == 0){
no + = 1
no_nos = 0
}其他{
no + = 1
seq_no + = 1
no_nos = 0
}
}
list
}

但是我真的不知道如何在不使用 vars 和while循环。



谢谢!

解决方案

以下代码产生与您的序列完全相同的序列:

<$ (1)
.flatMap(Stream.fill(2)(_))
.zipWithIndex
.flatMap(p){code> val seq = => Stream.fill(p._1)(p._2))
.tail



<但是,如果您想制作哥伦布序列(符合定义,但不同从您的示例代码结果中),您可以使用以下内容:

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

您可以检查我的文章更多关于如何处理功能风格的数字序列的例子。


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 so that S(1) = 1, and S(x) = the number of times x appears in the sequence. (I can't remember what this is called, but I've seen it in programming books before.)

In practice, the sequence looks like this:

  S = 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7 ...

I can generate this sequence pretty easily in Scala using an imperative style like this:

  def genSequence(numItems: Int) = {
    require(numItems > 0, "numItems must be >= 1")
    var list: List[Int] = List(1)
    var seq_no = 2
    var no     = 2
    var no_nos = 0
    var num_made = 1

    while(num_made < numItems) {
      if(no_nos < seq_no) {
        list = list :+ no
        no_nos += 1
        num_made += 1
      } else if(no % 2 == 0) {
        no += 1
        no_nos = 0
      } else {
        no += 1
        seq_no += 1
        no_nos = 0
      }
    }
    list
  }

But I don't really have any idea how to write this without using vars and the while loop.

Thanks!

解决方案

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.

这篇关于帮助重写功能风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆