当前位置:网站首页>Scala basic tutorial -- 13 -- advanced function
Scala basic tutorial -- 13 -- advanced function
2022-07-04 18:52:00 【Empty.】
Scala Basic course –13– Function advanced
Chapter goal
- Master the usage of functions as values and anonymous functions
- Understand the usage of coritization
- Master the usage of closures and control abstractions
- Master calculator case
1. Introduction to higher order functions
Scala Mixed object-oriented and functional features , In functional programming languages , The function is “ First-class citizen ”, It and Int、String、Class Other types are in the same position , Can be passed and manipulated like other types of variables . in other words , If the parameter list of a function can receive function objects , Then this function is called Higher order function (High-Order Function) . Like we learned before map Method , It can receive a function , complete List Transformation .
Commonly used higher-order functions have the following categories :
- Function as value
- Anonymous functions
- Closure
- Corey, wait
2. Function as value
stay Scala in , Functions are like numbers 、 The string is the same , You can pass a function object to a method . for example : We can encapsulate the algorithm , Then pass the specific action to the method , This feature is useful .
Example
demand
List an integer
List(1, 2, 3...) => *, **, ***
step
- Create a function , Used to replace numbers with a specified number of small stars
- Create a list , call map Method
- Print the converted list
Reference code
// Case study : Demo functions can be used as Object delivery .
object ClassDemo01 {
def main(args: Array[String]): Unit = {
// demand : Define a list , Record 1~10 Array of , Convert the number into the corresponding number *.
//1: * , 2: **, 3: ***...
//1. Define a list , Record 1~10 The number of .
val list1 = (1 to 10).toList
//2. Define a function object ( The function is Scala First class citizens in ), Used to put Int -> String
val func = (a:Int) => "*" * a
//3. Call function map, It's used to convert numbers .
//list1.map( Here we need a function )
val list2 = list1.map(func)
//4. Print the results .
println(list2)
}
}
3. Anonymous functions
summary
The above case , hold (num:Int) => "*" * num This function is assigned to a variable , Although the specified requirements are implemented , But this way of writing is a little wordy , We can go through Anonymous functions To optimize it . stay Scala in , Functions that are not assigned to variables are Anonymous functions .
Example
Through anonymous functions , Convert each element in an integer list into a corresponding number of small stars .
Reference code
// Case study : demonstration Anonymous functions .
object ClassDemo02 {
def main(args: Array[String]): Unit = {
// demand : Define a list , Record 1~10 Array of , Convert the number into the corresponding number *.
//1: * , 2: **, 3: ***...
//1. Define a list , Record 1~10 The number of .
val list1 = (1 to 10).toList
//2. adopt map Function is used for conversion , This function internally receives a : Anonymous functions .
val list2 = list1.map((a:Int) => "*" * a)
//3. Print the results .
println(list2)
// A simplified version : By underlining .
val list3 = list1.map("*" * _)
//val list4 = list1.map(_ * "*") // You can't write it like that , Will report a mistake .
println(list3)
}
}
4. currying
4.1 summary
stay scala and spark In the source code of , A large number of Coriolis . In order to facilitate our subsequent reading of the source code , We need to know about Corey . currying (Currying) Refer to The process of converting a method that previously accepted multiple parameters into a list of multiple parameters with only one parameter . Here's the picture :

4.2 Detailed explanation of process

4.3 Example
demand
Define methods , Complete the splicing of two strings .
Reference code
// Case study : Demonstrate coritization .
object ClassDemo03 {
// demand : Define methods , Complete the splicing of two strings .
// Mode one : Common writing .
def merge1(s1:String, s2:String) = s1 + s2
// Mode two : Kerry operation .
def merge2(s1:String, s2:String)(f1: (String, String) => String) = f1(s1, s2)
def main(args: Array[String]): Unit = {
// Call common writing
println(merge1("abc", "xyz"))
// Call curry writing .
println(merge2("abc", "xyz")(_ + _))
println(merge2("abc", "xyz")(_.toUpperCase() + _))
}
}
5. Closure
Closure refers to A function that can access data that is not in the current scope .
Format
val y = 10
val add = (x:Int) => {
x + y
}
println(add(5)) // result 1
Be careful : Coriolism is a closure .
demand
Define a function , Used to get the sum of two integers , Through the form of closures .
Reference code
// Case study : Demo closure .
object ClassDemo04 {
def main(args: Array[String]): Unit = {
// demand : Define a function , Used to get the sum of two integers .
//1. stay getSum Define a variable outside the function .
val a = 10
//2. Define a getSum function , Used to get the sum of two integers .
val getSum = (b:Int) => a + b
//3. Call function
println(getSum(3))
}
}
6. Control abstraction
Control abstraction is also a kind of function , It allows us to use functions more flexibly . Hypothesis function A The parameter list of needs to accept a function B, And the function B No input value, no return value , So the function A It's called Control abstraction function .
Format
val function A = ( function B: () => Unit) => {
// Code 1
// Code 2
//...
function B()
}
demand
- Define a function myShop, This function receives a function with no parameters and no return value ( hypothesis : The function name is f1).
- stay myShop Call in function f1 function .
- call myShop function .
Reference code
// Case study : Demonstrate control abstraction .
object ClassDemo05 {
def main(args: Array[String]): Unit = {
//1. Defined function
val myShop = (f1: () => Unit) => {
println("Welcome in!")
f1()
println("Thanks for coming!")
}
//2. Call function
myShop {
() =>
println(" I want to buy a notebook computer ")
println(" I want to buy a tablet ")
println(" I want to buy a mobile phone ")
}
}
}
7. Case study : Calculator
demand
- Write a method , Used to complete two Int Calculation of type numbers
- How to calculate and encapsulate functions
- Use coritization to achieve the above operation
Purpose
Investigate currying Related content .
Reference code
// Case study : Demonstrate coritization .
// currying (Currying): A parameter list with multiple parameters convert to Multiple parameter lists with only one parameter .
/* Example : Method name ( The number ){ // Is a method call , It just makes the method call more flexible . function } */
object ClassDemo06 {
// demand : Define a method , Used to complete the calculation of two integers ( for example : Add, subtract, multiply and divide ).
// Mode one : Common writing .
def add(a:Int, b:Int) = a + b
def subtract(a:Int, b:Int) = a - b
def multiply(a:Int, b:Int) = a * b
def divide(a:Int, b:Int) = a / b
// Mode two : Kerry operation .
// parameter list 1: Record the two data to be operated .
// parameter list 2: Record Specific operation ( Add, subtract, multiply and divide )
def calculate(a:Int, b:Int)(func: (Int, Int) => Int) = func(a, b)
def main(args: Array[String]): Unit = {
// Test common methods .
println(add(10, 3))
println(subtract(10, 3))
println(multiply(10, 3))
println(divide(10, 3))
println("*" * 15)
// Test the coriolisation method .
// The number function
println(calculate(7, 3)(_ + _))
println(calculate(7, 3)(_ - _))
println(calculate(7, 3)(_ * _))
println(calculate(7, 3)(_ / _))
}
}
边栏推荐
- Uni app and uviewui realize the imitation of Xiaomi mall app (with source code)
- 2022年字节跳动日常实习面经(抖音)
- 网上开户安全吗?是真的吗?
- [cloud voice suggestion collection] cloud store renewal and upgrading: provide effective suggestions, win a large number of code beans, Huawei AI speaker 2!
- 力扣刷题日记/day4/6.26
- Blue bridge: sympodial plant
- SIGMOD’22 HiEngine论文解读
- Interview summary of large factory Daquan II
- Scala基础教程--14--隐式转换
- I wrote a learning and practice tutorial for beginners!
猜你喜欢

The block:usdd has strong growth momentum

基于NCF的多模块协同实例

TorchDrug教程

Nature Microbiology | 可感染阿斯加德古菌的六种深海沉积物中的病毒基因组

Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology

Tutorial on the use of Huawei cloud modelarts (with detailed illustrations)

ISO27001认证办理流程及2022年补贴政策汇总

力扣刷题日记/day7/2022.6.29

MySQL common add, delete, modify and query operations (crud)

Blue bridge: sympodial plant
随机推荐
Stars open stores, return, return, return
Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii
【211】go 处理excel的库的详细文档
1、 Introduction to C language
Blue bridge: sympodial plant
Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join
2022年DCMM认证全国各地补贴政策汇总
Android uses sqliteopenhelper to flash back
MXNet对GoogLeNet的实现(并行连结网络)
Wireshark抓包TLS协议栏显示版本不一致问题
同事悄悄告诉我,飞书通知还能这样玩
The money circle boss, who is richer than Li Ka Shing, has just bought a building in Saudi Arabia
Digital "new" operation and maintenance of energy industry
The block:usdd has strong growth momentum
[daily question] 871 Minimum refueling times
[211] go handles the detailed documents of Excel library
6.26CF模拟赛E:价格最大化题解
Grain Mall (I)
如何提高开发质量
Russia arena data releases PostgreSQL based products