Is there an equivalent python reduce () function in scala?

I just started learning Scala and functional programming, and I'm trying to convert the following from Python to Scala:

def immutable_iterative_fibonacci(position):

    if (position ==1):
        return [1]

    if (position == 2):
        return [1,1]

    next_series = lambda series, _: series + [series [-1] + series [-2]]
    return reduce(next_series, range(position - 2), [1, 1])

I can't figure out what is equivalent to shortening in Scala. This is what I have now. Everything works fine except for the last line.

def immutable_fibonacci(position: Int) : ArrayBuffer[Int] = {

    if (position == 1){
          return ArrayBuffer(1)
     }

     if (position == 2){
         return ArrayBuffer(1,1)
     }

     var next_series = (series: ArrayBuffer[Int]) => series :+ ( series( series.size - 1) + series( series.size -2))

     return reduce(next_series, 2 to position, ArrayBuffer(1,1))
}
+4
source share
1 answer

Python Summary reduce, for reference:

reduce(function, iterable[, initializer])

Traversable

A good type to view is Traversablesupertype ArrayBuffer. You can just learn this API for a while, because there is a lot of useful stuff.

To reduce

Python reduce, initializer , Scala Traversable[A]#reduceLeft:

reduceLeft[B >: A](op: (B, A) => B): B

iterable Python Traversable, arg function Python op.

, reduce, reduceRight, reduceLeftOption reduceRightOption, , .

Fold

, initializer, Scala Traversable[A]#foldLeft:

foldLeft[B](z: B)(op: (B, A) => B): B

initializer Python z arg foldLeft.

, fold foldRight.

, :

def fibonacci(position: Int): Seq[Int] =
  position match {
    case 1 => Vector(1)
    case 2 => Vector(1, 1)
    case _ =>
      (2 to position).foldLeft(Vector(1, 1)) { (series, _) =>
        series :+ (series(series.size - 1) + series(series.size - 2))
      }
  }

:

  • return
  • (, match) , if - else
  • var ( ) val ( ),
  • (ArrayBuffer), . Vector .

Fibonacci, Stream:

val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #::
  fibs.zip(fibs.tail).map { n => n._1 + n._2 }

fibs.drop(1).take(6).mkString(" ")
// "1 1 2 3 5 8"
+11

Source: https://habr.com/ru/post/1654523/


All Articles