当前位置:网站首页>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"))
}
}
边栏推荐
- android使用SQLiteOpenHelper闪退
- [2022 Jiangxi graduate mathematical modeling] curling movement idea analysis and code implementation
- Redis主从复制
- 力扣刷题日记/day2/2022.6.24
- 输入的查询SQL语句,是如何执行的?
- 力扣刷题日记/day7/6.30
- Reptile elementary learning
- [system disk back to U disk] record the operation of system disk back to U disk
- 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
- 线上MySQL的自增id用尽怎么办?
猜你喜欢

VMware Tools和open-vm-tools的安装与使用:解决虚拟机不全屏和无法传输文件的问题
![[cloud native] what is the](/img/00/0cb0f38bf3eb5dad02b3bc4ead36ba.jpg)
[cloud native] what is the "grid" of service grid?

基于unity的愤怒的小鸟设计

Scala基础教程--20--Akka

TCP两次挥手,你见过吗?那四次握手呢?

Mxnet implementation of googlenet (parallel connection network)

Thawte通配符SSL证书提供的类型有哪些

Scala基础教程--19--Actor

TorchDrug教程

一直以为做报表只能用EXCEL和PPT,直到我看到了这套模板(附模板)
随机推荐
力扣刷题日记/day5/2022.6.27
[go ~ 0 to 1] read, write and create files on the sixth day
Weima, which is going to be listed, still can't give Baidu confidence
中国农科院基因组所汪鸿儒课题组诚邀加入
怎么开户才是安全的,
I wrote a learning and practice tutorial for beginners!
An example of multi module collaboration based on NCF
基于NCF的多模块协同实例
Deleting nodes in binary search tree
Journal des problèmes de brosse à boutons de force / day6 / 6.28
【2022年江西省研究生数学建模】冰壶运动 思路分析及代码实现
输入的查询SQL语句,是如何执行的?
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)
【云端心声 建议征集】云商店焕新升级:提有效建议,赢海量码豆、华为AI音箱2!
Just today, four experts from HSBC gathered to discuss the problems of bank core system transformation, migration and reconstruction
Is it safe to open an account online? is that true?
Unity 制作旋转门 推拉门 柜门 抽屉 点击自动开门效果 开关门自动播放音效 (附带编辑器扩展代码)
Imitation of numpy 2
The block:usdd has strong growth momentum
基于C语言的菜鸟驿站管理系统