Learn scala-second chapter control structure and function

Source: Internet
Author: User

Knowledge Points:

1. Conditional expression if (x>0) 1 Else 0

Scala each expression has a type, if it is the same type, and if it is a mixed-type expression, the public superclass of any.
if (x>0) 1 may not have output values, in Scala, each expression should have some value, introducing the Unit class, writing ().

if (x>0) 1 is equivalent to if (x>0) 1 else ()

2. Statement termination, if you write a long statement, you need to write in two lines, it is necessary to ensure that the first line with a symbol can not be used as the end of the sign, usually with the operator.

3. Block expressions and assignments, the value of the last expression in the block is the value of the block, the value of the assignment statement is the unit type, and therefore cannot be threaded together.

4. Print: Print\println, use the ReadLine function to read a line of input from the console with Readint, ReadByte, readdouble, Readshort, Readlong, Readfloat, Readboolean , Readchar read different numeric characters.

5. Cycle

for (i <-expression) let the variable i traverse all the values of the <-right-hand expression

To method: 1 to N returns a range of numbers 1 through n (inclusive), and the Until method returns an interval that does not contain an upper bound.

for (i <-0 until "Scala". Length) equals for (I <-"Scala")

You can provide multiple generators in the form of variable <-expressions separated by semicolons, each of which can take a guard.

for (I <-1 to 3, J <-1 to 3 if I! = j) Print ((Ten * I +j) + "")//will print 12 13 21 23 31 32

For deduction: If the loop body of the For loop starts with yield, the loop constructs a collection, each iteration generating a value in the collection. The set generated by the for deduction is type-compatible with its first generator.

for (I <-1 to ten) yield I% 3//Vector generated (1,2,0,1,2,0,1,2,0,1)

6. The method operates on an object, not a function. Scala's functions also include names, parameters, and function bodies. The type of all parameters must be given, as long as the function is not recursive (the compiler cannot verify the return type of the recursive function), it does not need to specify the return type, and the value of the last expression in the function body is the function return value.

7. The default parameters and named parameters of the function, the number of relative parameters, the given value is not enough, the default parameters will be applied one by one, the name parameter does not need to be exactly the same as the order of the parameter list, if you mix unnamed and named parameters, as long as those unnamed parameters are in the front.

8. Variable length parameters

def sum (args:int*) ={var result = 0; for (Arg <-args) result + = arg; result}

val s = SUM (1,2,3,4,6)

The function gets a parameter of type SEQ and accesses each element with a for loop. But if there is already a worthwhile sequence, you cannot pass directly into the function, and you need to tell the compiler that it expects this parameter to be treated as a parameter sequence, appended by: _*.

val s = sum (1 to 5:_*)

9. Procedure: If the function body is enclosed in curly braces but does not have the preceding = sign, then the return type is unit, such a function becomes a procedure and the procedure does not return a value.

10. When Val is declared as lazy, its initialization is deferred until it is first evaluated. Lazy values are useful for expensive initialization statements, which are in the middle of Val and Def, where Val is valued when defined, and when lazy is used for the first time, and the DEF is used every time the value is taken.

11. Exception Scala does not have a "picked up" exception, and it is not necessary to declare that a function or method might throw some kind of exception. The controller will recover from the processor closest to the throw point, and if no exception handler is found that meets the requirements, the program exits. The throw expression has a special type of nothing, which is useful in if/else expressions, and if the type of a branch is nothing, then the type of If/else is the type of the other branch.

Exercise: (Refer to the information downloaded from CSDN)

1. If a number is positive, its signum is 1, and if it is negative, Signum is-1; if 0, then Signum is 0. write a function to calculate the value.

Scala> def signum (num:int) ={     | var r=0     if(num>0) r=1     Elseif( num<0) r=-1     else r=0     | r}signum: (num:int) Intscala> Print (Signum (5))1 Scala> Print (signum (0))0Scala> Print (Signum ( -8))-1

Be sure to note that the return value of the function has an equal sign, or it returns the unit. R=–1, the equals sign and the minus sign are separated, otherwise the error "value =-is not a member of Int".

This method is already available in Scala.

Scala> BigInt (5= 1

2. What is the value of an empty block expression {}? What is the type?

Scala> print ({}) () Scala> Def test={}test:unitscala> var kong == ()

The type is unit and the value is ().

3. It is pointed out that in Scala, the assignment statement X=y=1 is legal. (Hint: Find an appropriate type definition for x)

The book says that the type of assignment statement is unit, so it is legal to define the type unit for x.

scala> var x== () Scala> var y=1= 1Scala> x=y=0= ()

4. Write a Scala version for the following Java loops:

for (int i=10;i>=0;i–) System.out.println (i);

 for (I <-0 to reverse) print (i+ "\ n")

5. Write a procedure countdown (N:int) to print numbers from N to 0.

Scala> def countdown (n:int) {     for (i-<-0 to n reverse     )| print (i+ "")     /c6>| }countdown: (n:int) Unitscala> Countdown (5)5 4 3 2 1 0

6. Write A For loop that calculates the product of the Unicode code for all the letters in the string. For example, the product of all strings in "Hello" is 9415087488L.

scala> var l:long = 1= 1Scalafor (i <-"Hello") {     | l=l*i.tolong     /c5>| }scala>= 9415087488

7. It is also a matter of solving the previous exercise, but this time do not use loops. (Hint: see Stringops in Scaladoc)

scala> var t:long = 1= 1Scala> Scala. foreach (t *= _.tolong) Scala>  = 11569118220

8. Write a function product (s:string) to calculate the product mentioned in the previous exercise.

scala> def product (s:string): long={     | var t:long = 1 for     (i <- s) {     | t *= I.tolong     |  }     | T     | }product: (s:string) Longscala> Print (Product ("Scala"))11569118220

9. Change the function in the previous exercise to a recursive function

scala> def product (s:string): long={     ifreturn s.charat (0). Tolong      Else s.take (1). charAt (0). Tolong * Product (S.drop (1))     | } Product: (s:string) Longscala> Print (Product ("Scala"))11569118220

10. Write the function to calculate xn, where n is an integer, using the following recursive definition:

Xn=y2, if n is a positive even number, here's y=x (N/2)

xn = x*x (n-1), if n is a positive odd number

x0 = 1

xn = 1/x (-n), if n is a negative number

You must not use the return statement.

Scala> def mten (x:double,n:int):D ouble={     if(n==0) 1     Elseif(n>0 && n%2==0) Mten (X,N/2) * Mten (X,N/2)     Elseif(n>0 && n%2==1) x * Mten (x , n-1)     Else 1/mten (x,-N)     | } Mten: (x:double, N:int) Doublescala> Print (mten (2,3))8.0Scala> Print (Mten (2,-3 ))0.125

Learn scala-second chapter control structure and function

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.