当前位置:网站首页>Scala basic tutorial -- 15 -- recursion
Scala basic tutorial -- 15 -- recursion
2022-07-04 18:53:00 【Empty.】
Scala Basic course –15– recursive
Chapter goal
- Understand the overview of recursion
- Master factorial cases
- Master the Fibonacci series case
- Master the case of printing catalog files
1. recursive
Recursion refers to Method calls its own situation
. When it comes to complex operations , We will often use it . When using recursion , Pay attention to the following three points :
- Recursion must have an exit , Otherwise, it is easy to cause Dead recursion .
- Recursion must be regular .
- Construction methods cannot be recursive .
- Recursive methods must have The data type of the return value .
for example : The following code is written recursively .
def show() = {
show()
}
2. Case a : Find the factorial
2.1 summary
The so-called factorial actually refers to Numbers 1 The cumulative multiplication result to this number
, for example 5 The factorial of is equivalent to 5 * 4 * 3 * 2 * 1
, 4 The factorial of is equivalent to 4 * 3 * 2 * 1
, According to the above description , We can draw two conclusions :
- The factorial formula is ( for example : Ask for numbers n The factorial ): n! = n * (n - 1)!
- 1 The factorial of is equal to 1, namely : 1! = 1
2.2 demand
Calculation 5 The factorial .
2.3 Reference code
// Case study : seek 5 The factorial .
object ClassDemo01 {
//1. Define methods , Used to find numbers n The factorial .
def factorial(n:Int):Int = if(n == 1) 1 else n * factorial(n - 1)
def main(args: Array[String]): Unit = {
//2. call factorial Method , Used to obtain 5 The factorial .
val num = factorial(5)
//3. Print the results .
println(num)
}
}
2.4 Memory diagram
summary
stay Scala in , Memory is divided into five parts , Respectively Stack , Pile up , Method area , Local method area , register , The characteristics are as follows :
- Stack
function :
Execution of all code .
Store local variables .
characteristic : according to First in, then out Sequential execution , The method is recycled immediately after execution . - Pile up :
function : Store all new What's coming out ( namely : object ).
characteristic : Be GC Recycling . - Method area :
function : Store bytecode files , Methods and other data .
characteristic : After the program is executed , Recycling resources by the operating system . - Local method area :
and Local method relevant , Understanding can . - register
and CPU relevant , Understanding can .
Factorial diagram
3. Case 2 : Fibonacci sequence
3.1 summary
It is said that there was an Italian youth named Fibonacci
, One day he raised a very interesting question , hypothesis :
- A pair of little rabbits will grow into a pair of big rabbits in a month .
- Every pair of big rabbits gives birth to a pair of little rabbits every month .
- Assuming that all rabbits do not die , ask : 1 To the little rabbit , 1 How many pairs of rabbits will it become after years ?
3.2 Thought analysis
namely : Known sequence 1, 1, 2, 3, 5, 8, 13…, ask : The first 12 What's the number ?
3.3 Reference code
// Case study : Fibonacci sequence
object ClassDemo02 {
//1. Define methods , Used to obtain the logarithm of rabbits .
def rabbit(month:Int):Int = {
if(month == 1 || month == 2) 1
else rabbit(month -1) + rabbit(month - 2)
}
def main(args: Array[String]): Unit = {
//2. Calling method , For the first 12 A couple of months .
val num = rabbit(12)
//3. Print the results .
println(num)
}
}
4. Case three : Print catalog file
4.1 demand
- Definition printFile(dir:File) Method , This method receives a file directory , Used to print all the file paths in this directory .
- stay main Test in method printFile() Method .
4.2 Purpose
Investigate recursive , Java Of File class Related content .
Be careful : because Scala It's dependence JVM Of , therefore Java Class library in , Scala It can also be called seamlessly ,
4.3 Reference code
import java.io.File
// Case study : Get all the files in the specified directory .
object ClassDemo03 {
//1. Definition printFile() Method , Used to print all file information under the specified directory .
def printFile(dir: File): Unit = {
if (!dir.exists()) {
println(" The path you entered does not exist ")
} else {
val listFiles:Array[File] = dir.listFiles()
for(listFile <- listFiles) {
if(listFile.isFile) println(listFile)
else printFile(listFile)
}
}
//2.main Method , As the main entrance to the program .
def main(args: Array[String]): Unit = {
//3. Calling method show()
printFile(new File("d:\\abc"))
}
}
边栏推荐
- "In Vietnam, money is like lying on the street"
- With an estimated value of 90billion, the IPO of super chip is coming
- Scala基础教程--13--函数进阶
- Wireshark packet capturing TLS protocol bar displays version inconsistency
- Digital "new" operation and maintenance of energy industry
- The controversial line of energy replenishment: will fast charging lead to reunification?
- 【机器学习的数学基础】(一)线性代数(Linear Algebra)(上+)
- Principle and application of ThreadLocal
- 力扣刷题日记/day8/7.1
- C language printing exercise
猜你喜欢
MySQL common add, delete, modify and query operations (crud)
[HCIA continuous update] network management and operation and maintenance
基于C语言的菜鸟驿站管理系统
Mxnet implementation of googlenet (parallel connection network)
Scala基础教程--17--集合
[go ~ 0 to 1] read, write and create files on the sixth day
[mathematical modeling of graduate students in Jiangxi Province in 2022] analysis and code implementation of haze removal by nucleation of water vapor supersaturation
Once the "king of color TV", he sold pork before delisting
【Go语言刷题篇】Go完结篇|函数、结构体、接口、错误入门学习
2022 national CMMI certification subsidy policy | Changxu consulting
随机推荐
输入的查询SQL语句,是如何执行的?
What if the self incrementing ID of online MySQL is exhausted?
力扣刷题日记/day8/7.1
[HCIA continuous update] WAN technology
Reptile elementary learning
[210] usage of PHP delimiter
Imitation of numpy 2
力扣刷题日记/day1/2022.6.23
An example of multi module collaboration based on NCF
Li Kou brush question diary /day2/2022.6.24
Nature Microbiology | 可感染阿斯加德古菌的六种深海沉积物中的病毒基因组
完善的js事件委托
Neglected problem: test environment configuration management
Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers
【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)
MXNet对GoogLeNet的实现(并行连结网络)
李迟2022年6月工作生活总结
【209】go语言的学习思想