当前位置:网站首页>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)(_ / _))
}
}
边栏推荐
- 6.26CF模拟赛E:价格最大化题解
- 输入的查询SQL语句,是如何执行的?
- The money circle boss, who is richer than Li Ka Shing, has just bought a building in Saudi Arabia
- 如何提高开发质量
- 被忽视的问题:测试环境配置管理
- 线上MySQL的自增id用尽怎么办?
- Uni app and uviewui realize the imitation of Xiaomi mall app (with source code)
- My colleagues quietly told me that flying Book notification can still play like this
- celebrate! Kelan sundb and Zhongchuang software complete the compatibility adaptation of seven products
- 李迟2022年6月工作生活总结
猜你喜欢
Unity 制作旋转门 推拉门 柜门 抽屉 点击自动开门效果 开关门自动播放音效 (附带编辑器扩展代码)
Stars open stores, return, return, return
Li Kou brush question diary /day4/6.26
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
力扣刷题日记/day1/2022.6.23
Uni app and uviewui realize the imitation of Xiaomi mall app (with source code)
ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development
With the stock price plummeting and the market value shrinking, Naixue launched a virtual stock, which was deeply in dispute
MXNet对GoogLeNet的实现(并行连结网络)
随机推荐
SIGMOD’22 HiEngine论文解读
Nature microbiology | viral genomes in six deep-sea sediments that can infect Archaea asgardii
Interview summary of large factory Daquan II
网上开户安全吗?是真的吗?
C语言打印练习
VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
android使用SQLiteOpenHelper闪退
[cloud native] what is the "grid" of service grid?
Scala基础教程--18--集合(二)
Li Kou brush question diary /day4/6.26
李迟2022年6月工作生活总结
如何提高开发质量
力扣刷題日記/day6/6.28
Li Kou brush question diary /day2/2022.6.24
Is it safe to download the mobile version of Anxin securities and open an account online
【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
一种将Tree-LSTM的强化学习用于连接顺序选择的方法
[211] go handles the detailed documents of Excel library
"In Vietnam, money is like lying on the street"
Android uses sqliteopenhelper to flash back