34

Introduction to scala for a c programmer

Embed Size (px)

Citation preview

Page 1: Introduction to scala for a c programmer
Page 2: Introduction to scala for a c programmer

INTRODUCTION TO SCALA

BY:- GIRISH KUMAR A L

PART I

Page 3: Introduction to scala for a c programmer

1. Martin Odersky

2. General purpose programming language.

3. It blends in “Object Oriented” and “functional Programming” paradigms.

4. SCALA’s innovations come primarily from how its constructs are put together.

What is SCALA ?

Page 4: Introduction to scala for a c programmer

Functional Programming:Is a programming paradigm where we try to divide programs

into functions, which have no side effects i.e. don’t change program state and void mutable data. Eliminating side effects can make it much easier to understand and predict the behavior of a program.

What is SCALA ?

Page 5: Introduction to scala for a c programmer

Object-oriented-programming: Is a programming paradigm where programs are divided into containers called Objects which have data fields and behavior(methods). SCALA is a pure OOP language.

What is SCALA ?

Page 6: Introduction to scala for a c programmer

1. SCALA was written keeping in mind that “its impractical” to come-up with a new programming language and make it widely acceptable without interoperating with applications from Java.

2. “Java code can call SCALA code” and “SCALA code can can java code”. Scala gets compiled into Java Byte codes, which gets executed on Java virtual machine.

SCALA and JAVAJAVA

SCALA

C++C

Page 7: Introduction to scala for a c programmer

1. So, SCALA was written for Java programmers ?.

2. Most of the courses, books and tutorials assume that you already know java or at least OOP.

But

SCALA AND JAVA

Page 8: Introduction to scala for a c programmer

There is no shortcut here.

First go and learn Java , or at least go here : http://docs.oracle.com/javase/tutorial/java/index.html , and ramp up on Basic OOP concepts.

New and important features of SCALA such as pattern matching, Traits and compositions need OOP concepts.

Even basic language constructs like If-else, for loops, function declarations and definitions, etc. are quite different , and not only with respect to syntax.

SCALA for a C language PROGRAMMER.

Page 9: Introduction to scala for a c programmer

1. A lot of interesting companies like Twitter, Foursquare and LinkedIn are using/adopting SCALA.

2. There are even some VIM plugins around.

3. Good build tool support like SBT, Maven, Ant etc..

4. SCALA is now in its v2.10. Lot of new features every release.

5. And it is not like IPv4 to IPv6 transformation. It must be fairly easy for java based applications to port to SCALA.

BUT why SCALA ?

Page 10: Introduction to scala for a c programmer

1. Variables in SCALA. 1. Variable Immutability.2. Type inference.

2. Functions in SCALA.1. Anonymous Functions.

3. SCALA control constructs.1. If expression.2. For expression.

4. Pattern Matching.1. With Constants.2. With Regular expressions.

SOME attractive features OF scala

Page 11: Introduction to scala for a c programmer

When programming in C, If we want a variable, most of us will be thinking in these steps

1. I need an Integer

int

Variables in SCALA: VAL AND VAR

Page 12: Introduction to scala for a c programmer

1.Let me give it a name “x”, that declares x. This is enough we can go ahead ,but…

int x;

VAL AND VAR

Page 13: Introduction to scala for a c programmer

1. Let me initialize it to 0, to be safe. This defines x(allocates memory)

int x = 0;

VAL AND VAR

Page 14: Introduction to scala for a c programmer

In SCALA we will have to think in this way:

1. I need a mutable or a immutable field? i.e. val or var ? Lets go with a val.

val

VAL AND VAR

Page 15: Introduction to scala for a c programmer

2. Let me name it “x”.

val x

VAL AND VAR

Page 16: Introduction to scala for a c programmer

3. OK I need it to be an Integer

val x: Int

VAL AND VAR

Page 17: Introduction to scala for a c programmer

3. Let me initialize it to 0. This ends the value definition.

val x: Int = 0

4. But scala has “Type inference” right!? Why do I need to type it as “Int”. Yes we can omit it. Its enough just to have this:

val x = 0

VAL AND VAR

Page 18: Introduction to scala for a c programmer

val s = “STRING”

var x = (1, “ONE”)

TYPE inference in SCALA

Page 19: Introduction to scala for a c programmer

Function DEFINITIONSIn C

int factorial(int x) {if(x == 1)

return x;else

return x * factorial(x - 1);}

Page 20: Introduction to scala for a c programmer

Function Definitions• In SCALA

• def factorial(x: Int): Int = { if(x == 1) x

else x * factorial(x - 1)

}

• So this function is of type (Important!)

• (Int) => Int

Page 21: Introduction to scala for a c programmer

Function Definitions• If there is no parameter to function!

• def function1(): Int = {255

• }

• We can even forget about () and Int!!

• def function2 = {• 1 + 2• } // These functions are of type () => Int

Page 22: Introduction to scala for a c programmer

Function Definitions• If the function is not returning anything then we can forget about

“=”

def function3 {//Body}

If the function body is of only one line then we can even forget about “{ }”

def function4 = 1

Page 23: Introduction to scala for a c programmer

FUNCTION LITERALS1. Also called as Anonymous Functions, these functions are not

bound to an identifier. Can be written in below format in SCALA.

(x: Int, y:Int) => (x+y)

2. These functions can be passed as arguments to “Higher-order functions”.

def higherOrderFunc(f: (Int, Int) => Int) : Int;

Page 24: Introduction to scala for a c programmer

SCALA IF EXPRESSIONIt looks similar to if in C, but SCALAS “if” is an expression. So it returns a value.

if(!args.isEmpty) args(0) else “default.txt”

And it can be used inside function calls, and as function bodies.println(if(!args.isEmpty) args(0) else “default.txt”)

ORdef function(args: Array[String]): String =

if(!args.isEmpty) args(0) else “default.txt”

Page 25: Introduction to scala for a c programmer

SCALA FOR EXPRESSIONFor expression in SCALA is the Swiss army knife of iteration.

for ( generator definition filter)

1. Iteration through an Array.for (x <- 0 to 100)

OR

for (x <- 0 until 100)OR just

for(x <- args)

Page 26: Introduction to scala for a c programmer

SCALA FOR EXPRESSION2. Using Filters

for ( x <- 1 to 100 if x%2 == 0) println(x)

You can use multiple filters :

for { x <-1 to 100 if x%2 == 0 if x%3 == 0 } println(x)

for (x <- args if x.matches(“^\\d*$”)) println(x)

Page 27: Introduction to scala for a c programmer

SCALA FOR EXPRESSION3. Using definitions

for (x <- args y = x.length if y <= max) println(x)

4 . Multiple Generators:

for (x <- args y <- x) println(y)

5. Returning from a for expression using Yield

val y = for(x <- 1 to 100 if x%3 == 0) yield x

Page 28: Introduction to scala for a c programmer

Pattern Matching Pattern matching in scala is done with the help of a construct called match which looks similar to c language switch.

Simple example: pattern matching with constants

x match {case “-help” | “-h” => displayHelpcase “-version” | “-v” => displayVersioncase _ => process

}

Page 29: Introduction to scala for a c programmer

Pattern Matching with Regular expressionsA simple example, with regular expressions

val regex = "(^\\d*$)".r

def patternMatch(x: String) = x match {case regex(a) => println("matched")case _ => println("Did Not matched")

}

patternMatch("1234")patternMatch("abcd")

Page 30: Introduction to scala for a c programmer

Comparable features C SCALA

Programming paradigm Imperative programming Functional and object oriented programming

Compiler Compiled to machine code Compiled to Byte codes

High-level Data-structures No Language support, but libraries are added on top using primary data types

Lists[T], Maps[T,M], Set[T], SortedSet[T,M]

Concurrency With Help of locks and shared-memory With help of actors, share nothing strategy. But still supports locks and shared-memory.

Scripting No scripting support Scripting support

Memory management Logic has to be built into the application code to free allocated memory.

Garbage collector frees memory as soon as it goes out of scope

Pattern Matching No support Pattern matching with help of case classes, regular expressions.

Performance Benchmarking Highly optimized C ++ , short run time code is about 3 times faster.

-----------

Debuggability / Maintenance Difficult to debug as everything is mutable Much easier to debug as mostly everything can be immutable.

Development Longer development time. Most concise language constructs reduce development time and number of lines of code by half compared to Java.

KEY DIFFRENCES BETWEEN C AND SCALA

Source: Google benchmarks C++, Go, Java and SCALA Performance

Page 31: Introduction to scala for a c programmer

Other Features of SCALA1. Singleton Objects.2. Pattern Matching with case classes.3. Stackable features with Traits.4. Companion objects and Factory Methods.5. Synchronized collections. 6. Concurrent programming with Actors.

These and more can be covered in Part II.

Page 32: Introduction to scala for a c programmer

References1. Official Scala API database:http://www.scala-lang.org/api/current/index.html#package

2. Programming in SCALA second edition by Martin Odersky

3. Scala Tutorial at http://www.tutorialspoint.com/scala/index.htm

Page 33: Introduction to scala for a c programmer

Q & A

Page 34: Introduction to scala for a c programmer

THANK YOU