Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Scala Note arrangement (5): functional programming

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

[TOC]

A function passed as a value

The test code is as follows:

Operations on functions in package cn.xpleaf.bigdata.p4.function/** * scala * / object _ 01FunctionOps {def main (args: Array [String]): Unit = {functionOps1} / * functions passed as values * when passing a function as a value to another function variable, the convention needs to add: spaces and underscores * equivalent to aliases in the database Or the view corresponding to the database table * / def functionOps1: Unit = {def sayHi (name:String) = println ("Hello," + name) def sayHello = sayHi _ sayHello ("xpleaf")}}

The output is as follows:

Hello, xpleaf anonymous function

The test code is as follows:

Operations on functions in package cn.xpleaf.bigdata.p4.function/** * scala * / object _ 01FunctionOps {def main (args: Array [String]): Unit = {functionOps2} / * Anonymous functions. To put it bluntly, there is no function name * Anonymous functions, like anonymous inner classes in java, are suitable for use only once * generally if the argument of a function is a function In this case, anonymous functions are often used as arguments * / def functionOps2: Unit = {val printName = (name:String) = > println ("Hello," + name) printName ("xpleaf")}}

The output is as follows:

Hello, xpleaf.

In fact, anonymous functions have already been used when learning ArrayBuffer:

Scala > val ab = ArrayBuffer [Int] (3,8,2,20,5,7) ab: scala.collection.mutable.ArrayBuffer [Int] = ArrayBuffer (3,8,2,20,5,7) scala > ab.sortWith ((v1, v2) = > v1 > v2) res209: scala.collection.mutable.ArrayBuffer [Int] = ArrayBuffer (20,8,7,5,3,2) function with function parameters (higher order function)

The description serves two purposes (the anonymous function as a parameter and the return value as an anonymous function). Refer to the following test code:

The higher-order function of package cn.xpleaf.bigdata.p4.function/** * scala about the operation of function * / object _ 01FunctionOps {def main (args: Array [String]): Unit = {/ / functionOps1// functionOps2 functionOps3} / * scala is the function whose parameter is a function. This function is called higher-order function * / def functionOps3: Unit = {/ / 1. Anonymous function as parameter def highOrderFunc (name:String, func: (String) = > Unit): Unit = {func (name)} highOrderFunc ("xpleaf", (name:String) = > println ("Hello," + name)) / / 2. Pass an anonymous function as a return value to another function def getGoodBayFunction (gMsg: String) = (gName: String) = > println (gMsg + "," + gName) val goodbayFunction = getGoodBayFunction ("good bye") goodbayFunction ("xpleaf")}}

The output is as follows:

Hello, xpleafgood bye, xpleaf parameter (type) inference

The test code is as follows:

Operations on functions in package cn.xpleaf.bigdata.p4.functionimport scala.collection.mutable.ArrayBuffer/** * scala * / object _ 01FunctionOps {def main (args: Array [String]): Unit = {/ / functionOps1// functionOps2// functionOps3 functionOps4} / * ellipsis for anonymous functions * / def functionOps4: Unit = {val ab = ArrayBuffer [Int] (1,2,3,4) 5) / / val newAB = ab.map ((x:Int) = > x * 100) / / val newAB = ab.map ((x) = > x * 100) / / val newAB = ab.map (x = > x * 100) val newAB = ab.map (100,200,300,400,500)}}

The output is as follows:

ArrayBuffer (100,200,300,400,500) common high-order functions-the map function traverses every element in the collection and returns a set that is the same size as the previous set. Rapid generation of 0.1,0.2 Number scala > (1 to 9) .map (0.1 * _) .foreach (println (_)) 0.10.20.3000000000000040.40.50.600000000000010.7000000000010.80.9 print triangle scala > (1 to 9) .map ("*" * _) .foreach (println (_)) *

Here, we also use foreach, which is very similar to map, except that its function does not return any value, foreach simply applies the function to each element.

Filter function, a common high-order function, filters out all the elements that match a specific condition from the original set according to the filtering conditions. Get all the even numbers scala > (1 to 9) .filter (line = > line% 2 = = 0). Foreach (println (_)) 2468scala > (1 to 9). Filter (_% 2 = = 0). Foreach (println) 2468 common high-order functions-- reduce function scala > (1 to 9). Reduce ((v1:Int) V2:Int) = > v1 + v2) res4: Int = 45scala > (1 to 9). Reduce (_ + _) res6: Int = 45scala > (1 to 9). ReduceLeft (_ + _) res7: Int = 45scala > (1 to 9). ReduceRight (_ + _) res8: Int = 45

You can write the following function to verify the execution of the reduce function:

Scala > val process = (v1:Int, v2:Int) = > println (s "v1customers ${v1}, v2customers ${v2}") process: (Int, Int) = > Unit = scala > def pro (v1:Int, v2:Int): Int = {| println (s "v1examples ${v1}, v2customers ${v2}") | v1 + v2 |} pro: (v1:Int, v2:Int) Intreduce execution flow scala > (1 to 9). Reduce (v1:Int, v2:Int) = > pro (v1, v2)) v1room1 The execution flow of v2=2v1=3, v2=3v1=6, v2=4v1=10, v2=5v1=15, v2=6v1=21, v2=7v1=28, v2=8v1=36, v2=9res0: Int = 45reductLeft scala > (1 to 9). ReduceLeft ((v1:Int, v2:Int) = > pro (v1, v2)) v1, v2=2v1=3, v2=3v1=6, v2=4v1=10, v2=5v1=15, v2=6v1=21, v2=7v1=28, v2=8v1=36, v2=9res2: Int = 45reductRight execution flow scala > (1 to 9). ReduceRight (v1:Int, v2:Int) = > pro (v1, v2) v1q8, v2=9v1=7, v2=17v1=6, v2=24v1=5, v2=30v1=4, v2=30v1=4, v2=35v1=3, v2=35v1=3, v2=39v1=2, v2=39v1=2: v2=39v1=2 = 45

In this way, the execution process is very clear, reduce and reduceLeft start with the Operand on the left, while reduceRight starts with the Operand on the right.

Common high-order functions-- sortWith function scala > (1 to 9). SortWith ((v1:Int, v2:Int) = > v1 > v2). Foreach (println (_)) 987654321scala > (1 to 9). SortWith (_ > _). Foreach (println) 987654321 closure

The variable of a function is not called within its scope, which is the concept of closure. Take a look at the following example:

Def closePackage: Unit = {def mulBy (factor:Double) = (x:Double) = > factor * x val triple = mulBy (3) val half = mulBy (0.5) println (triple (14) + "+ half (14)) / / 42,7}

1) the first call to mulBy sets the parameter variable factor to 3. This variable is referenced in the body of the (x:Double) = > factor * x function. The function is stored in triple. The parameter variable factor is then popped up from the runtime stack.

2) mulBy is called again, and this time factor is set to 0. 5. This variable is referenced in the function body of the function (x:Double) = > factor * x, which is stored in half.

Each function is called a closure. Closures are made up of code and any nonlocal variable definitions used by the code.

In fact, the above mulBy function is similar to the following:

Def mulBy1 (factor:Double, x:Double) = {factor * x}

I had hoped to write it further like this:

Def mulBy2 (factor:Double, x:Double) = {def work (x:Double) = {factor * x} return work}

However, this method of writing is not supported in scala. This is the only way to write it:

Def mulBy2 (factor:Double) = {(x:Double) = > factor * x} / / not even with a return

Closures have been used in Python before. Similar to the example above, Python can write:

Def mulBy (factor): def work (x): return factor * x return work

The tests are as follows:

Def mulBy (factor):... Def work (x):... Return factor * x... Return work... > triple = mulBy (3) > half = mulBy (0.5) > triple (14) 42 > half (14) 7.0

Of course, the syntax format of Python is not as flexible as scala.

Corialization (currying function)

1. Currying refers to the process of changing a function that 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.

2. In the process of function call, it becomes the form of continuous call of two functions. In the Spark source code, it is also reflected, so the Curring function in the form of () () must be mastered.

The following function takes one parameter and generates another function that accepts a single parameter. To calculate the product of two numbers, call:

/ * curryingFunction: Corialization function * / def curryingFunction = {def totalSum (x:Int, y:Int) = println (x + y) / / totalSum (4Power5) def totalSumAtTime (x:Int) = (y:Int) = > x + y println (totalSumAtTime (4) (5))}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report