KEMBAR78
Introduction to scala for a c programmer | PPTX
INTRODUCTION TO SCALA
                       PART I
       BY:-   GIRISH KUMAR A L
What is SCALA ?
1. Martin Odersky

2. General purpose programming language.



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

2. SCALA’s innovations come primarily from how its constructs are
   put together.
What is SCALA ?
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 ?
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.
SCALA and JAVA
        SCALA
                              JAVA
                                               C++
                                                             C


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 JAVA
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 for a C language
                     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.
BUT why SCALA ?
1.    A lot of interesting companies like Twitter, Foursquare and
     LinkedIn are using/adopting SCALA.

1. There are even some VIM plugins around.

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

3. 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.
1.
     SOME attractive features OF scala
      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.
Variables in SCALA: VAL AND VAR
When programming in C, If we want a variable, most of us will be
thinking in these steps



1.    I need an Integer


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




                int x;
VAL AND VAR
1. Let me initialize it to 0, to be safe.   This defines x(allocates
memory)




                  int x = 0;
VAL AND VAR
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
2. Let me name it “x”.




               val x
VAL AND VAR
3. OK I need it to be an Integer




                  val x: Int
VAL AND VAR
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
TYPE inference in SCALA

val s = “STRING”

var x = (1, “ONE”)
Function DEFINITIONS
In C


int factorial(int x) {
 if(x == 1)
     return x;
 else
     return x * factorial(x - 1);
}
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
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
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
FUNCTION LITERALS
1. 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;
SCALA IF EXPRESSION
It 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”)
           OR
   def function(args: Array[String]): String =
       if(!args.isEmpty) args(0) else “default.txt”
SCALA FOR EXPRESSION
For 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)
SCALA FOR EXPRESSION
2. 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)
SCALA FOR EXPRESSION
3. 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
Pattern Matchinga construct called
Pattern matching in scala is done with the help of
match which looks similar to c language switch.

Simple example: pattern matching with constants

x match {
   case “-help” | “-h” => displayHelp
   case “-version” | “-v” => displayVersion
   case _       => process
}
Pattern Matching with Regular
                        expressions
A 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")
KEY DIFFRENCES BETWEEN C AND SCALA
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      Lists[T], Maps[T,M], Set[T], SortedSet[T,M]
                                   top using primary data types
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   Garbage collector frees memory as soon as it
                                   free allocated memory.                               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.

                 Source: Google benchmarks C++, Go, Java and SCALA Performance
1.
          Other Features of SCALA
     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.
1.
                        References
   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
Q&A
THANK YOU

Introduction to scala for a c programmer

  • 2.
    INTRODUCTION TO SCALA PART I BY:- GIRISH KUMAR A L
  • 3.
    What is SCALA? 1. Martin Odersky 2. General purpose programming language. 1. It blends in “Object Oriented” and “functional Programming” paradigms. 2. SCALA’s innovations come primarily from how its constructs are put together.
  • 4.
    What is SCALA? 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.
  • 5.
    What is SCALA? 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.
  • 6.
    SCALA and JAVA SCALA JAVA C++ C 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.
  • 7.
    SCALA AND JAVA 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
  • 8.
    SCALA for aC language 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.
  • 9.
    BUT why SCALA? 1. A lot of interesting companies like Twitter, Foursquare and LinkedIn are using/adopting SCALA. 1. There are even some VIM plugins around. 2. Good build tool support like SBT, Maven, Ant etc.. 3. 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.
  • 10.
    1. SOME attractive features OF scala 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.
  • 11.
    Variables in SCALA:VAL AND VAR When programming in C, If we want a variable, most of us will be thinking in these steps 1. I need an Integer int
  • 12.
    VAL AND VAR 1.Letme give it a name “x”, that declares x. This is enough we can go ahead ,but… int x;
  • 13.
    VAL AND VAR 1.Let me initialize it to 0, to be safe. This defines x(allocates memory) int x = 0;
  • 14.
    VAL AND VAR InSCALA 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
  • 15.
    VAL AND VAR 2.Let me name it “x”. val x
  • 16.
    VAL AND VAR 3.OK I need it to be an Integer val x: Int
  • 17.
    VAL AND VAR 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
  • 18.
    TYPE inference inSCALA val s = “STRING” var x = (1, “ONE”)
  • 19.
    Function DEFINITIONS In C intfactorial(int x) { if(x == 1) return x; else return x * factorial(x - 1); }
  • 20.
    Function Definitions • InSCALA • def factorial(x: Int): Int = { if(x == 1) x else x * factorial(x - 1) } • So this function is of type (Important!) • (Int) => Int
  • 21.
    Function Definitions • Ifthere 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
  • 22.
    Function Definitions • Ifthe 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
  • 23.
    FUNCTION LITERALS 1. Alsocalled 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;
  • 24.
    SCALA IF EXPRESSION Itlooks 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”) OR def function(args: Array[String]): String = if(!args.isEmpty) args(0) else “default.txt”
  • 25.
    SCALA FOR EXPRESSION Forexpression 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)
  • 26.
    SCALA FOR EXPRESSION 2.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)
  • 27.
    SCALA FOR EXPRESSION 3.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
  • 28.
    Pattern Matchinga constructcalled Pattern matching in scala is done with the help of match which looks similar to c language switch. Simple example: pattern matching with constants x match { case “-help” | “-h” => displayHelp case “-version” | “-v” => displayVersion case _ => process }
  • 29.
    Pattern Matching withRegular expressions A 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")
  • 30.
    KEY DIFFRENCES BETWEENC AND SCALA 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 Lists[T], Maps[T,M], Set[T], SortedSet[T,M] top using primary data types 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 Garbage collector frees memory as soon as it free allocated memory. 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. Source: Google benchmarks C++, Go, Java and SCALA Performance
  • 31.
    1. Other Features of SCALA 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.
  • 32.
    1. References 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
  • 33.
  • 34.

Editor's Notes

  • #12 In C we think I need an IntegerLet me name it XLet me initialize it to 0In ScalaI need value/Variable?
  • #13 In C we think I need an IntegerLet me name it XLet me initialize it to 0In ScalaI need value/Variable?
  • #14 In C we think I need an IntegerLet me name it XLet me initialize it to 0In ScalaI need value/Variable?
  • #15 This is where you explain what is a val
  • #16 This is not enough if it a method local mutable/immutable you need more ?
  • #17 This is not enough if it a method local mutable/immutable you need more ?
  • #18 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #19 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #20 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #21 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #22 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #23 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #24 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #25 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #26 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #27 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #28 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #29 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #30 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #32 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #33 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #34 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does
  • #35 Now lets make it more simple, Doesn&apos;t’t scala have “Type inference” ? Yes it does