简体   繁体   English

函数式编程:scala中的递归循环输出斐波那契序列

[英]functional programming: recursive loop output fibonacci sequence in scala

Learning functional programming using scala. 使用Scala学习函数式编程。 Came across this exercise. 进行了此练习。

Write a recursive function to get the nth Fibonacci number ( http://mng.bz/C29s ). 编写一个递归函数以获取第n个斐波那契数( http://mng.bz/C29s )。 The first two Fibonacci numbers are 0 and 1. The nth number is always the sum of the previous two—the sequence begins 0, 1, 1, 2, 3, 5. Your definition should use a local tail-recursive function. 前两个斐波那契数是0和1。第n个数字始终是前两个数之和-序列以0、1、1、2、3、5开头。您的定义应使用局部尾递归函数。

def fib(n: Int): Int

My answer computes n+1 values and returns the nth. 我的答案计算n + 1个值并返回第n个。 Can anyone show me a better implementation where the extra n+1th value is not computed? 谁能给我展示一个更好的实现,其中不计算额外的n + 1个值?

object patterns {

    def fib(n : Int): Int = {
        @annotation.tailrec
        def go(n: Int, prev2: Int, prev: Int): Int =
            if(n<=0) prev2 
            else go(n-1, prev, prev2+prev)
        go(n, 0, 1)
      }
}

In case anyone is interested, this is from the book functional programming in scala by Chiusano and Bjarnason. 如果有人感兴趣,这是Chiusano和Bjarnason在scala中编写的《函数编程》一书。 Exercise 2.1 Looking forward to the replies. 练习2.1期待答复。

I think this: 我认为这:

def fib2(n: Int): Int = {
  if (n < 1) 0
  else if (n < 2) 1
  else {
    @annotation.tailrec
    def go(i: Int, prev2: Int, prev: Int): Int =
      if (i == n) prev
      else go(i + 1, prev, prev2 + prev)
    go(2, 1, 1)
  }
}

or using ByName param: 或使用ByName参数:

def fib3(n: Int): Int = {
  @annotation.tailrec
  def go(n: Int, prev2: Int, prev: => Int): Int =
    //                            ^ ByName
    if (n <= 0) prev2
    else {
      val p = prev
      go(n - 1, p, prev2 + p)
    }
  go(n, 0, 1)
}

I like to use stream to implement it. 我喜欢使用stream来实现它。 Because the code is shorter and easier to understand. 因为代码更短,更容易理解。

      def fibo():Stream[Int] = {
        def addRec(o1:Int,o2:Int):Stream[Int] = {
          o1 #:: addRec(o2,o1 + o2)
        }
        addRec(1,1)
      }

      println(fibo().take(100).toList)  

get the nth is simple to call fibo.drop(n-1)(0) 获得nth很容易调用fibo.drop(n-1)(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM