当前位置:网站首页>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)(_ / _))
}
}
边栏推荐
- 激进技术派 vs 项目保守派的微服务架构之争
- . Net ORM framework hisql practice - Chapter 2 - using hisql to realize menu management (add, delete, modify and check)
- [go ~ 0 to 1] read, write and create files on the sixth day
- 力扣刷题日记/day2/2022.6.24
- LD_ LIBRARY_ Path environment variable setting
- [211] go handles the detailed documents of Excel library
- 中国农科院基因组所汪鸿儒课题组诚邀加入
- How is the entered query SQL statement executed?
- Redis master-slave replication
- MySQL common add, delete, modify and query operations (crud)
猜你喜欢

celebrate! Kelan sundb and Zhongchuang software complete the compatibility adaptation of seven products

Grain Mall (I)

Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction

基于unity的愤怒的小鸟设计

Wireshark packet capturing TLS protocol bar displays version inconsistency

如何提高开发质量

Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers

Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join

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

输入的查询SQL语句,是如何执行的?
随机推荐
[211] go handles the detailed documents of Excel library
Scala基础教程--15--递归
谷粒商城(一)
Pb extended DLL development (super chapter) (VII)
Numpy 的仿制 2
Behind the ultra clear image quality of NBA Live Broadcast: an in-depth interpretation of Alibaba cloud video cloud "narrowband HD 2.0" technology
Interview summary of large factory Daquan II
[209] go language learning ideas
怎么开户才是安全的,
Once the "king of color TV", he sold pork before delisting
[go ~ 0 to 1] read, write and create files on the sixth day
蓝桥:合根植物
Tutorial on the use of Huawei cloud modelarts (with detailed illustrations)
I always thought that excel and PPT could only be used for making statements until I saw this set of templates (attached)
VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
能源行业的数字化“新”运维
Wanghongru research group of Institute of genomics, Chinese Academy of Agricultural Sciences is cordially invited to join
Nature Microbiology | 可感染阿斯加德古菌的六种深海沉积物中的病毒基因组
How is the entered query SQL statement executed?
Uni app and uviewui realize the imitation of Xiaomi mall app (with source code)