페이지

2015년 10월 29일 목요일

Scala2e Chapter3 Next Steps in Scala - Step 11. Learn to recognize the functional style

Two style code.

imperative style : if code ontains any vars
functional style : it contains only vals

imperative style:

def printArgs(args: Array[String])):Unit ={
   var i =0
   while (i < args.length) {
       println(args(i))
        i +=1
    }
}

your can transform this bit of code into a more functional style by getting rid of the var, for example, like this.

def printArgs(args: Array[String]): Unit = {
    for( arg <- args="" div="" nbsp="">
       println(arg)
}

or this:


def printArgs(args: Array[String]: Unit = {
    args.foreach(println)
}

Benefit of programming with fewer vars.
- The refactoryed(more functional) code is clearer.
- More concise
- less error-prone than the original(more imperative) code.

The telltale sign of a function with side effects is that its result type is Unit. 
If a function isn't returning any interesting value, which is what a result type of Unit means, the only way that function can make a difference in the world is through some kind of side effect.

2015년 10월 28일 수요일

Scala2e Chapter3 Next Steps in Scala - Step 10. Use sets and maps

Because Scala aims to help you take advantage of both functional and imperative styles, is collections libraries make a point to differentiate between mutable and immutable collections.

For example, the Scala API contains a base trait for sets, where a trait is similar to Java interface.

Scala the providers two subtraits, on for mutable sets and another for immutable sets.

var jetSet = Set("Boeing", "Airbus")
jetSet += "Lear"
println(jetSet.contains("Cessna"))


To add a new element to a set, you call + on the set, passing in the new element. Both mutable and immutable sets offers a + method, but their behavior differs. 
Whereas a mutable set will add the element to itself, an immutable set will create and return a new set with the element added. 

import scala.collection.mutable.Set

val movieSet = Set("Hitch", "Poltergeist")
movieSet += "Shrek"
println(movieSet)


The mutable set by calling the += method on the set.

import scala.collection.immutable.HashSet

val hashSet = HashSet("Tomatoes", "Chilies")
println(hashSet + "Coriander")




There's base Mat trait in package scala.collection, and two subtrait Maps: a mutable Map in scala.collection.mutable and an immutable one in scala.collection.immutable.

import scala.collection.mutable.Map

val treasureMap = Map[Int, String]()
treasureMap  += (1 -> "Go go island.")
treasureMap  += (2 -> "Find big X on ground.")
treasureMap  += (3 -> "Dig.")

println(treasureMap(2))

The map is empty because you pass nothing to the factory method(the parentheses in "Map[Int, String]()" are empty).
This -> method, which you can invoke on any object in a Scala program, returns a two-element tuple containing the key and value.

If you prefer an immutable map, no import is necessary, as immutable is the default map.

val romanNumeral = Map(
1->"I", 2 ->"II", 3 ->"III", 4->"IIII", 5 ->"IIIII")

println(romanNumeral(4))








2015년 10월 27일 화요일

Scala2e Chapter3 Next Steps in Scala - Step 9. Use tuples

Tuples are immutable.
Tuples can contain different type of elements.

val pair = (99, "Luftballons")
println(pair._1)
println(pair._2)

apply method always retuns the same type, but each element of a tuple may be a different type: _1 can have one result type, _2 another, and so on.
These _N numbers are one-based, instead of zero-base, because string with 1 is a tradition set by other lanaguages with statically typed tuples, such as Haskell and ML.



Scala2e Chapter3 Next Steps in Scala - Step 8. Use lists

The functional style of programming is that methods should not have side effects.
A method's only act should be to compute and return a value.
- less entangled
- more reliable
- reusable

Applying this functional philosophy to the world of objects means making objects immutable.

Scala Lists are always immutable(whereas Java Lists can be mutable).
More generally, Scala's List is designed to enable a functional style of programming.

val onTwoThress = List(1,2,3)

val onTwo = List(1,2)
val threeFour = List(3,4)
val oneTwoThreeFour = oneTwo ::: threeFour
println(oneTwo + " and " + threeFour + " were not mutated.")
println("Thus, "+ onTwoThreeFour + " is a new list.")

If you run this script, you'll see:

List(1,2) and List(3,4) were not mutated.
Thus, List(1,2,3,4) is a new List.

List has method named ':::' for list concatenation.
 '::' is pronounced "cpns."
Cons prepends a new element to the beginning of an existiong list, and returns the resulting list.

val thwThree = List(2,3)
val oneTwoThree = 1 :: twoThree
println(oneTwoThree)

You'll see:
List(1,2,3)





Scala2e Chapter3 Next Steps in Scala - Step 7. Parameterize arrays with type

In Scala, you can instantiate objects, or class instances, using new.
When you instantiate an object in Scala, you can parameterize it with values and types.

The follwing Scala coe instantiates a new java.math.BigInteger and parameterizes it with the value "12345"

val big = new java.math.BigInteger("12345")


val greetString = new Array[String](3)

greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"


for(i <- 0="" 2="" p="" to="">print(greetStrings(i))




val greetStrings : Array[String] = new Array[String](3)

greetString(0) = "Hello"
greetString(1) = ", "
greetString(2) = "world!\n"

These three lines of code illustrate an important concept to understand about Scala concerning the meaning of val. When you define a variable with val, the variable can't reassigned, but the object to which it refers could potentially still be changed. So in this case, you couldn't be reassign greetStrings to a different array; greetStrings will always point to the same Array[String] instance with which it was initialized. But you can changed the elements of that array[String] instance with which it was initialized. But you can change the elements of that Array[String] over time, so the array itself is mutable.

for( i <- 0="" 2="" p="" to="">  print(greetString(i))

The code 0 to 2 is transformed into the method call (0).to(2).
Note that this syntax only works if you explicitily specify the receiver of the method call. You cannot write "println 10", but you can write "Console println 10".


greetStrings(0) = "Hello"  => greetStrings.update(0,"Hello")

val greetStrings = new Array[String](3)
greetStrings.update(0,"hello")
greetStrings.update(1,", ")
greetStrings.update(2, "world!\n")

for(i <- 0.to="" p="">   print(greetStrings.apply(i))








Scala2e Chapter2 First Steps in Scala - Step 6. Iterate with foreach and for

Step 6. Iterate with foreach and for

The functional style as you are with imperative style.

args.foreach(arg => println(arg))

$ scala pa.scala  Concise is nice

Concise
in
nice

args.foreach ((arg: String) => println(arg))



Now, by this point you may be wondering what happened to those trusty for loops you have been accustomed to using in imperative languages such as Java or C. In an effort to guide you in a functional direction, only a functional relative of the imperative for is available in Scala.

In a new file named forargs.scala, type the following:

for(arg <- args="" p="">println(arg)

for each element of the args array, a new arg val will be created and initialized to the element value, and the body of the for will be executed

$scala forargs.scala for arg in args

for
arg
in
args




2015년 10월 22일 목요일

Scala2e Chapter2 First Steps in Scala - Step5. Loop with while; decide with if

Step5. Loop with while; decide with if

To try out a while, type the following into a file named printargs.scala:

var i = 0
while (i < args.length) {
println(args(i))
i += 1
}

The first statement, println(args(i)), prints out the ith command line argument.
The second statement, i += 1, increments i by one. Note that Java’s ++i and i++ don’t work in Scala. i = i + 1 or i += 1.

$ scala printargs.scala Scala is fun

Scala
is
fun

For even more fun, type the following code into a new file with the name echoargs.scala:
var i = 0
while (i < args.length) {
if (i != 0)
print(" ")
print(args(i))
i += 1
}
println()

$ scala echoargs.scala Scala is even more fun

Scala is even more fun

Scala does use semicolons to separate statements as in Java, except that in Scala the semicolons are very often optional, giving some welcome relief to your right little finger.

echoargs.scala script as follows:

var i = 0;
while (i < args.length) {
if (i != 0) {
print(" ");
}
print(args(i));
i += 1;
}
println();

Scala2e Chapter2 First Steps in Scala - Step4. Write some Scala scripts

Step4. Write some Scala scripts

A script is just a sequence of statements in a file that will be executed sequentially.

Put this into a file named hello.scala:

println("Hello, world, from a script!")

$ scala hello.scala

Hello, world, from a script!

To try this out, type the following into a new file named helloarg.scala
// Say hello to the first argument

println("Hello, "+ args(0) +"!")

$ scala helloarg.scala planet

Hello, planet!


2015년 10월 20일 화요일

Scala2e Chapter2 First Steps in Scala - Step3. Define some functions

Step3. Define some functions

scala> def max(x: Int, y: Int): Int = {
if (x > y) x
else y
}
max: (x: Int,y: Int)Int

scala> max(3, 5)
res4: Int = 5


scala> def greet() = println("Hello, world!")
greet: ()Unit

Scala’s Unit type is similar to Java’s void type

Scala2e Chapter2 First Steps in Scala - Step2. Define some variables

Step 2. Define some variables

val - final variable in Java. Once initialized, a val can never be reassigned

var - similar to a non-final variable in Java. A var can be reassigned throughout its lifetime

scala> val msg = "Hello, world!"
msg: String = Hello, world!

This example illustrates type inference, Scala’s ability to figure out types you leave off.
In this case, because you initialized msg with a string literal, Scala inferred the type of msg to be String.
Scala interpreter (or compiler) can infer type.

scala> val msg2: java.lang.String = "Hello again, world!"
msg2: String = Hello again, world!

scala> val msg3: String = "Hello yet again, world!"
msg3: String = Hello yet again, world!

The simple name of java.lang.String is String

scala> println(msg)
Hello, world!

scala> msg = "Goodbye cruel world!"
:6: error: reassignment to val
msg = "Goodbye cruel world!"


scala> var greeting = "Hello, world!"
greeting: String = Hello, world!

scala> greeting = "Leave me alone, world!"
greeting: String = Leave me alone, world!

scala> val multiLine =
| "This is the next line."
multiLine: String = This is the next line.

scala> val oops =
|
|
You typed two blank lines. Starting a new command.
scala>


Scala2e Chapter2 First Steps in Scala - Step1. Learn to use the Scala interpreter

Step1. Learan to use the Scala interpreter

• an automatically generated or user-defined name to refer to the computed value (res0, which means result 0),
• a colon (:), followed by the type of the expression (Int),
• an equals sign (=),
• the value resulting from evaluating the expression
If you’re not familiar with Java packages, you can think of them as providing a full name for classes. Because Int is a member of package scala, “Int” is the class’s simple name, and “scala.Int” is its full name. The resX identifier may be used in later lines. For instance, since res0 was set to 3 previously, res0 * 3 will be 9:



To print the necessary, but not sufficient, Hello, world! greeting, type:

scala> println("Hello, world!")
Hello, world!

The println function prints the passed string to the standard output, similar
to System.out.println in Java.