Scala is a new language that combines functional language and object-oriented language. In this document, I will write down some of scala's experiences, focusing mainly on functional programming.
1. Recursive control structure as the core.
There are three methods to implement loop processing: goto, for/while, and recursion. The implementation of loop with goto has been abandoned in modern languages, and structured programming in the form of for/while has become the mainstream, recursion, as another solution, has long been popular only in small circles of functional programming.
The main concern for recursion in the mainstream programming world is the deep call stack. Even in the past, we tried to rewrite recursion into a loop, but in modern functional programming languages, through the form of tail recursion (which will be discussed later), recursion can effectively optimize its call stack to the same level as the loop.
To solve the call stack problem, the advantage of recursion is shown as follows: recursion is concise and descriptive. In the real world, many computations share self-similarity, which is exactly the feature of recursion. Compared with the loop, it does not need so many identification variables to process the loop. Instead, it models A computing process as a "self-similar" calculation. As long as the local logic in a small range is correctly implemented, the logic of any range can be correctly implemented.
The sample code is as follows: ''' // The Newton method is used to obtain the square root def sqrt (value: Double, trial: Double): Double = {def isGoodEnough (trial: Double ): boolean = abs (trial * trial-value) <0.0001 def abs (value: Double): Double = {if (value <0) return-value else return value} println (value, trial) if (isGoodEnough (trial) trial else sqrt (value, (trial + value/trial)/2 )}
Println (sqrt (2, 1 ))'''