Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to scala for a c programmer

476 views

Published on

  • Be the first to comment

  • Be the first to like this

Introduction to scala for a c programmer

  1. 1. INTRODUCTION TO SCALA PART I BY:- GIRISH KUMAR A L
  2. 2. What is SCALA ?1. Martin Odersky2. 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.
  3. 3. What is SCALA ?Functional Programming: Is a programming paradigm where we try to divide programs intofunctions, which have no side effects i.e. don’t change program stateand void mutable data. Eliminating side effects can make it mucheasier to understand and predict the behavior of a program.
  4. 4. What is SCALA ?Object-oriented-programming: Is a programming paradigm where programs are divided intocontainers called Objects which have data fields andbehavior(methods). SCALA is a pure OOP language.
  5. 5. SCALA and JAVA SCALA JAVA C++ C1. SCALA was written keeping in mind that “its impractical” tocome-up with a new programming language and make it widelyacceptable without interoperating with applications from Java.2. “Java code can call SCALA code” and “SCALA code can can javacode”. Scala gets compiled into Java Byte codes, which gets executedon Java virtual machine.
  6. 6. SCALA AND JAVA1. 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
  7. 7. 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 onBasic 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.
  8. 8. 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.
  9. 9. 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.
  10. 10. Variables in SCALA: VAL AND VARWhen programming in C, If we want a variable, most of us will bethinking in these steps1. I need an Integer int
  11. 11. VAL AND VAR1.Let me give it a name “x”, that declares x. This is enough we can goahead ,but… int x;
  12. 12. VAL AND VAR1. Let me initialize it to 0, to be safe. This defines x(allocatesmemory) int x = 0;
  13. 13. VAL AND VARIn 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
  14. 14. VAL AND VAR2. Let me name it “x”. val x
  15. 15. VAL AND VAR3. OK I need it to be an Integer val x: Int
  16. 16. VAL AND VAR3. Let me initialize it to 0. This ends the value definition. val x: Int = 04. 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
  17. 17. TYPE inference in SCALAval s = “STRING”var x = (1, “ONE”)
  18. 18. Function DEFINITIONSIn Cint factorial(int x) { if(x == 1) return x; else return x * factorial(x - 1);}
  19. 19. 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
  20. 20. 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
  21. 21. 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
  22. 22. 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;
  23. 23. SCALA IF EXPRESSIONIt looks similar to if in C, but SCALAS “if” is an expression. So itreturns 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”
  24. 24. 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)
  25. 25. 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)
  26. 26. 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
  27. 27. Pattern Matchinga construct calledPattern matching in scala is done with the help ofmatch which looks similar to c language switch.Simple example: pattern matching with constantsx match { case “-help” | “-h” => displayHelp case “-version” | “-v” => displayVersion case _ => process}
  28. 28. Pattern Matching with Regular expressionsA simple example, with regular expressionsval regex = "(^d*$)".rdef patternMatch(x: String) = x match { case regex(a) => println("matched") case _ => println("Did Not matched")}patternMatch("1234")patternMatch("abcd")
  29. 29. KEY DIFFRENCES BETWEEN C AND SCALAComparable features C SCALAProgramming paradigm Imperative programming Functional and object oriented programmingCompiler Compiled to machine code Compiled to Byte codesHigh-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 typesConcurrency 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 supportMemory 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 scopePattern 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
  30. 30. 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.
  31. 31. 1. References Official Scala API database:http://www.scala-lang.org/api/current/index.html#package2. Programming in SCALA second edition by Martin Odersky3. Scala Tutorial athttp://www.tutorialspoint.com/scala/index.htm
  32. 32. Q&A
  33. 33. THANK YOU

×