Programming in Scala (Second Edition) reading notes 7 built-in control structure

Source: Internet
Author: User
Tags vars

1. One thing you'll notice is, almost all of Scala's control structures result in some value

Every control statement in Scala is a value.

The approach taken by functional languages

Which programs is viewed as computing a value, thus the components of a

Program should also compute values

This is because the functional language thinks that the function of a program is to calculate a value, so its individual components should also calculate a value

2. While loop

def gcdloop (A:int, b:int): Int = {var x = A; var y = b var tmp = 0 while (Y! = 0) {tmp = y y = x% y x = tmp} X

3. Do. While loop

var line = "" Does {line = ReadLine () println ("Read:" + Line)} while (line! = "")}

4. Unit

The while and Do-while constructs is called "loops," not expressions,

Because they don ' t result in an interesting value. The type of the result is

Unit. It turns out of a value (and in fact, only one value) exists whose type

Is Unit. It is called the unit value and is written (). The existence of () is

How Scala's Unit differs from Java ' s void

While and do are called loops rather than expressions because they do not produce any meaningful value, the meaningless value in Scala is called Unit, write (), and () exists in Scala's unit, which differs from Java's void.

Object Testsheet {def greet () {println ("hello!")}                                                  > Greet: () Unit greet = = ()//> hello! //| Res0:boolean = true}

5. A statement that assigns a value to Var also generates a unit

Object Testsheet {var a = 123//> A:int = 123 (A = 456) = = () > Res0:boolean = True}

6. Why Scala includes a while loop

Because the While loop results in no value, it's often left out of pure

Functional languages. Such languages has expressions, not loops. Scala

Includes the while loop nonetheless, because sometimes a imperative solution can be more readable, especially to Programm ERs with a predominantly

Imperative background. For example, if you want to code a algorithm that

Repeats a process until some condition changes, a while loop can express it

Directly while the functional alternative, which likely uses recursion

Less obvious to some readers of the code

Because no value is generated, a purely functional language usually does not contain a while loop, whereas Scala contains a while loop. This is because sometimes the imperative language solution is more readable, especially for people with command-language programming backgrounds

In general, we recommend your challenge while loops in your code in the

Same the challenge VARs. In fact, while loops and vars often go hand

In hand. Because while loops don ' t result in a value, to do any kind of

difference to your program, a while loop would usually either need to update

VARs or perform I/O.

Try not to use while loops and Var unless forced

While loops usually occur at the same time as Var because while loops want to make a difference, either change the value of Var or perform I/O operations


7.For-expression

Scala's for expression is a Swiss army knife of iteration. It lets you combine

A few simple ingredients in different ways to express a wide variety of iterations. Simple uses enable common tasks such as iterating through a sequence

of integers. More advanced expressions can iterate over multiple collections

of different kinds, can filter out elements based on arbitrary conditions, and

can produce new collections.

Scala's for expression is an iterative Swiss * * *. You can combine simple compositions in different ways to express diverse iterations.

The simplest application is to iterate over an integer sequence.

An advanced point of application involves iterating over multiple sets of different types

can be filtered or used to generate a new collection


8. List all files of a directory (Listing files in a directory with a for expression)

Object Testmain {def main (args:array[string]) {val files = (new Java.io.File ("e:/")). Listfiles () for (File <-fi Les) println (file)}}

9. The fall generation on the Range object

for (I <-1 to Ten) println ("Iteration:" + i)

Equivalent to

for (I <-1 until) println ("Iteration:" + i)

10. filter files ending in. txt

val files = (new Java.io.File ("e:/")). Listfiles () for (file <-files if File.getname (). EndsWith (". txt")) println (file)

11. Multiple Filter conditions

val files = (new Java.io.File ("e:/")). Listfiles () for (File <-files if File.getname (). EndsWith (". txt") if file.g Etname (). StartsWith ("Data")) println (file)

12. Multiple iterations (nested iteration)

For {shape <-List ("Hearts", "Plum", "block", "spades") Num <-1 to "println" (Shape+num)

You must use curly braces here.

13. The For statement above can also include the IF condition

For {shape <-List ("Hearts", "Plum", "block", "spades") Num <-1 to 3 if num% = = 0} println (shape+num)

14. Iterative generation of new collections

Syntax: for clauses yield body

Val oddnums = for (i <-1 to ten if I% 2 = 0) yield i println (oddnums)//vector (2, 4, 6, 8, 10)

Try...finally ... The return value

def f:int = try {1} finally {2}//> f: = = Int F//&G T Res0:int = 1

Not 2, but 1, it must have been unexpected.


A. Match statement

Val line = ReadLine () line match {case "yes" + println ("Your input is yes") case "no" + println ("Got No") Case _ = = println ("Not what I expected")}

A value is returned in the match statement

The match statement can be used for very complex pattern matching, just to illustrate the simplest usage


17. Print the multiplication table

Package chapter7object testmain {  def main (args: array[string])  {//  make sequence    def makeseq (N: int)  = for  (i  &LT;-&NBSP;1&NBSP;TO&NBSP;9)   yield {      val prod =   (n * i) .tostring      val pading =  " "   *  (4 - prod.length)       pading + prod     }    // make row    def makerow (n: Int )  = makeseq (n). Mkstring    // make table    def  makeTable = {      val tableSeq = for  (R &NBSP;&LT;-&NBSP;1&NBSP;TO&NBSP;9)   yield {         Makerow (R)        }      tableseq.mkstring ("\ n")     }         println (maketable)     }}/* out put    1   2   3   4   5   6    7   8   9   2   4    6   8  10  12  14  16  18    3   6   9  12  15  18  21   24  27   4   8  12  16  20   24  28  32  36   5  10  15   20  25  30  35  40  45   6  12   18  24  30  36  42  48  54   7  14   21  28  35  42  49  56  63    8  16  24  32  40  48  56  64   72   9  18  27  36  45  54   63  72  81*/


Programming in Scala (Second Edition) reading notes 7 built-in control structure

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.