8.25. Scala function Corialization (Currying)

发布时间 :2023-11-17 23:00:02 UTC      

Currying refers to the process of changing a function that originally accepts two parameters into a new function that accepts one parameter. The new function returns a function that takes the original second argument as an argument.

8.25.1. Example #

First, let’s define a function:

def add(x:Int,y:Int)=x+y

So when we apply it, we should use it like this: add(1,2)

Now let’s transform this function:

def add(x:Int)(y:Int) = x + y

So when we apply it, we should use it like this: add(1)(2) in the end, the result is all the same, which is called Corialization.

8.25.2. Realization process #

add(1)(2) in fact, two ordinary functions (non-Corialized functions) arecalled in turn, the first call takes a parameter x and returns a value of afunction type, and the second call uses the parameter y to call the value of this function type.

In essence, it first evolved into such a method:

def add(x:Int)=(y:Int)=>x+y

So what does this function mean? Receives an x as an argument and returns ananonymous function defined as receiving a Int type parameter y, the body of the function is x+y . Now let’s call this method.

val result = add(1)

Returns a result , result should be an anonymous function (y:Int)=>1+y

So in order to get the results, we continue to call the result .

val sum = result(2)

The final printed result is 3.

8.25.3. Complete instance #

Here is a complete example:

object Test {
   def main(args: Array[String]) {
      val str1:String = "Hello, "
      val str2:String = "Scala!"
      println( "str1 + str2 = " +  strcat(str1)(str2) )
   }

   def strcat(s1: String)(s2: String) = {
      s1 + s2
   }
}

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
str1 + str2 = Hello, Scala!

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.