페이지

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