当前位置:网站首页>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)(_ / _))
}
}
边栏推荐
- Wireshark packet capturing TLS protocol bar displays version inconsistency
- 字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
- 一、C语言入门基础
- Detailed explanation of the maturity classification of ITSS operation and maintenance capability | one article clarifies the ITSS certificate
- Li Kou brush question diary /day8/7.1
- Scala基础教程--14--隐式转换
- 被忽视的问题:测试环境配置管理
- 线上MySQL的自增id用尽怎么办?
- Redis主从复制
- SIGMOD’22 HiEngine论文解读
猜你喜欢

Scala基础教程--13--函数进阶

力扣刷题日记/day4/6.26

Installation and use of VMware Tools and open VM tools: solve the problems of incomplete screen and unable to transfer files of virtual machines

I wrote a learning and practice tutorial for beginners!

Unity makes revolving door, sliding door, cabinet door drawer, click the effect of automatic door opening and closing, and automatically play the sound effect (with editor extension code)

DB engines database ranking in July 2022: Microsoft SQL Server rose sharply, Oracle fell sharply

Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg

Scala基础教程--18--集合(二)

字节跳动Dev Better技术沙龙成功举办,携手华泰分享Web研发效能提升经验
![[cloud native] what is the](/img/00/0cb0f38bf3eb5dad02b3bc4ead36ba.jpg)
[cloud native] what is the "grid" of service grid?
随机推荐
Li Kou brush question diary /day3/2022.6.25
Uni app and uviewui realize the imitation of Xiaomi mall app (with source code)
Wireshark抓包TLS协议栏显示版本不一致问题
Scala基础教程--15--递归
MySQL常用增删改查操作(CRUD)
一、C语言入门基础
一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)
力扣刷題日記/day6/6.28
Li Kou brush question diary /day7/2022.6.29
力扣刷题日记/day1/2022.6.23
2022 national CMMI certification subsidy policy | Changxu consulting
力扣刷题日记/day3/2022.6.25
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
Redis master-slave replication
项目通用环境使用说明
Is it safe to download the mobile version of Anxin securities and open an account online
Thawte通配符SSL证书提供的类型有哪些
[HCIA continuous update] WAN technology
输入的查询SQL语句,是如何执行的?
General environmental instructions for the project