[Scala] functional programming

Posted by blawson7 on Mon, 07 Mar 2022 00:33:51 +0100

Function definition and use

The most common way to define a function is as a member of a class or object. This function is called a method, and its basic syntax is

def Method name(parameter list):Result type={Method body}


Literal quantity includes integer literal quantity, floating-point literal quantity, Boolean literal quantity, character literal quantity, string literal quantity, symbol literal quantity, function literal quantity and tuple literal quantity

Function literal can reflect the core concept of functional programming

In functional programming, functions are "first-class citizens" and can be passed and manipulated like any other data type, that is, functions
Is used in exactly the same way as other data types

At this time, we can define a function like defining variables. As a result, the function will start to have "values" like other variables

Just as the "type" and "value" of a variable are two separate concepts, in functional programming, the "type" and "value" of a function also become two separate concepts. The "value" of a function is "function literal"

The following points will guide you to better understand the concepts of "type" and "value" of a function. Now define a function of traditional type that you are familiar with. The syntax of the definition is similar to the definition of "method in class" we introduced earlier (in fact, the most commonly used method for defining a function is as a member of an object, which is called a method):

def counter(value: Int): Int = { value += 1}

The type of the above function is: (int) = > int

Parentheses are required only when there are multiple parameters (the spacer between parameters is comma). Parentheses can be omitted when there is only one parameter

int => int

The type of function is obtained above

Now let's get the value of the function

In fact, we only need to remove the type declaration of the function definition to get the value of the function

(value) => {value += 1}

Now, we use Scala syntax to define a function according to the familiar way of defining variables.

When declaring a variable, we use the following form:

val num:Int = 5

Define the function in a similar way as above

val counter: Int => Int = { (value) => value += 1 }

As can be seen from the above, in Scala, functions are already "first-class citizens", and the concept of "value" is separated separately. The "value" of a function is the literal value of the function. As like as two peas, we declare a function type in a place where we need to declare the function, and then we can send a corresponding function literal volume when we call it, just like using the ordinary variable.

We don't need to name every function because we can use anonymous functions

(num:Int) => num*2

The above definition form of anonymous function is often called lambda expression. Lambda expression has the following form:

(parameter) => expression
//When there is only one parameter, the parentheses of the parameter can be omitted

Store anonymous functions directly into variables

    val NumFunc = (num: Int) => num * 2
    println(NumFunc(3))

The literal "= >" of each function parameter can be omitted only once, and can appear in "= >" of each function As a placeholder for parameters to simplify the representation of the number of functional areas, the first underline represents the first parameter, the second underline represents the second parameter, and so on

    val add = (_:Int) + (_:Int)
    println(add(4,5))

Jump top

Higher order function

Higher order function: when a function contains other functions as its parameters or the return result is a function, the function is called a higher-order function

Example: suppose you need to calculate the "continued sum", "square sum" and "power sum of 2" from one integer to another

Do not use caution function

  def powerOfTwo(x: Int): Int = {
    if (x == 0) 1 else 2 * powerOfTwo(x - 1)
  }

  def sumInts(a: Int, b: Int): Int = {
    if (a > b) 0 else a + sumInts(a + 1, b)
  }

  def sumSquares(a: Int, b: Int): Int = {
    if (a > b) 0 else a * a + sumSquares(a + 1, b)
  }

  def sumPowersOfTwo(a: Int, b: Int): Int = {
    if (a > b) 0 else powerOfTwo(a) + sumPowersOfTwo(a + 1, b)
  }

Using higher order functions

  def sum(f: Int => Int, a: Int, b: Int):Int = {
    if(a > b) 0 else f(a) + sum(f, a+1, b)
  }

Jump top

Operation for container

Traversal list
Scala traversal container standard writing

def foreach[U](f: Elem => U) :Unit

Use demo

    val list = List(1,2,3)
    val f = (i:Int) => println(i)
    list.foreach(f)

It can also be abbreviated into the following two ways

    list foreach(i => println(i))
    list foreach println

Traverse Map

    val map = Map("name" -> "Jack", "age" -> "21")
    //Detailed writing
    map foreach { kv => println(kv._1 + ":" + kv._2) }
    //Abbreviation
    map foreach { x => x match {
      case (k, v) => println(k + ":" + v)
    }
    }
    map foreach { case (k, v) => println(k + ":" + v) }

Jump top

Topics: Python Scala Front-end regex