Original: Scala Study Notes (continuously updated)

Source: Internet
Author: User

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 ))'''

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.