Scala sum example code

Time:2019-10-20

Scala is a multi paradigm programming language, which is designed to integrate various features of object-oriented programming and functional programming.

Scala runs on a Java virtual machine and is compatible with existing Java programs.

Scala source code is compiled into Java bytecode, so it can run on top of the JVM and call existing Java class libraries.

def sum(f: Int => Int)(a: Int)(b: Int): Int = {

  @annotation.tailrec
  def loop(n: Int, acc: Int): Int = {
   if (n > b) {
    println(s"n=${n},acc=${acc}")
    acc
   } else {
    println(s"n=${n},acc=${acc}")
    loop(n + 1, acc + f(n))
   }
  }
  loop(a, 0)
 }    
 sum(x => x)(1)(5)
 sum(x => x*x)(1)(5)
 //Use wildcards
 val sumSqure = sum(x => x * x)_ 
 sumSqure(1)(5)

=>It can be understood as a mapping relationship
Corrilization and partial application function

Recommended Today

How to check the package according to the command in CentOS

In our work, we often encounter that we want to use a command machine that is not installed, but we don’t know which package the command is in (source compilation is not covered in this article). Here is a rather stupid method to help us solve this problem. Explain:Blue = command name Light green = […]