Presentation is loading. Please wait.

Presentation is loading. Please wait.

“Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE

Similar presentations


Presentation on theme: "“Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE"— Presentation transcript:

1 “Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE
Scalable Language “Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE

2 Overview History Design Goals Components of Scala Sample Code
Memory Management Real-Life Application Replace with general terms

3 History Marin Odersky Java Compiler and Java Generics Pizza (1996)
Programming Methods Laboratory (LAMP) Swiss Federal Institute of Technology in Lausanne (EPFL) Timeline 2001 development began 2003 internal release 2004 first official announcement 2006 Java 2.0 Martin Odersky wrote the Java Compiler and Java Generics Runs the Programming Methods Laboratory (LAMP) group at Swiss Federal Institute of Technology Pizza compiled to Java byte code Uses Scala as a research and teaching language

4 Design Goals Integrate object-oriented programming and functional programming Functional: E.g. pass functions as arguments OO: has classes, everything is an object Wanted to design a language built on the JVM Express programs in concise, elegant, and type-safe way Statically bound types Strongly typed Can look very script-y Similar to Java, OO and functions, concise and elegant -> pull that into examples (continue to tie back to this slide) Tie how each feature connects back to a goal Could add stuff about scripting language

5 Everything is an object
Scala is a pure object-oriented language as everything is an object Java is not a pure OO language - has primitive types (like boolean and int) Even numbers and functions are objects Since numbers are objects they have methods 1 + 2 (1).+(2) 1 + 2 is the same things as saying (1).+(2)

6 Binding Addresses Scala uses the JVM so stack/heap allocation are the same References and primitives on stack, Objects on heap Scala doesn’t have primitives, but types (like Int or Long) get compiled to the JVM’s primitive types in bytecode whenever possible JVM attempts OSR (on Stack Replacement) of variables Objects stored on stack, when JVM determines it’s safe to do that

7 Data Types & Structures
Byte, short, int, long, float, double, char, string, boolean,unit, null, nothing, any, anyref Many of the same data structures as Java Arrays, Lists, Sets, Maps Tuple Like a list but can hold objects with different types val x = (10, “Scala”) nothing - subtype of every other type any - supertype of any type - any object is of type any anyref - supertype of any reference type Lists are linked lists

8 A Scala Class class Rational(n: Int, d: Int) {
private val g = gcd(n, d) val numer: Int = n/g val denom: Int = d/g private def gcd(x: Int, y: Int): Int = { if (x == 0) y else if (x < 0) gcd(-x, y) else if (y < 0) -gcd(x, -y) else gcd(y % x, x) } def +(that: Rational) = new Rational(numer * that.denom + that.numer * denom,denom *that.denom) Class definition includes parameters (Java does not have parameters) Must contain parameter types Contains private method inside the class Fields correspond to the parameters if/else statement - notice no curly braces Script-y style with no “;” to end the line Can override opertor

9 Variables Scala is statically typed and variables are statically bound
When writing code, there are few explicit type definitions because Scala can usually infer the type E.g. val x = 3 compiler infers that 'x' must be type Int as '3' is a integer literal. I Variables in Scala can be declared as either mutable or immutable All variables and functions have types and are determined at compile time If compiler cannot infer the type it will generate a type ambiguity error, and you simply add the intended type annotation.

10 Mutable Variables Mutable variables can be changed after they are defined In Java: int x = 5 In Scala: var i = 1 // type inferencing done by compiler var i : Int = 5 Second definition of i is exactly the same

11 Immutable Variables Immutable variables cannot be changed once they’ve been assigned In Java: final int x = 1 In Scala: val i = 1 i += 1 // returns an error since i has been declared immutable Val defines a constant Variables that are immutable are calculated when the code block containing val is entered Also have something called lazy val which aren’t calculated until the first time the variable is accessed Used if cost of calculating is very long

12 A Scala Class class Rational(n: Int, d: Int) {
private val g = gcd(n, d) val numer: Int = n/g val denom: Int = d/g private def gcd(x: Int, y: Int): Int = { if (x == 0) y else if (x < 0) gcd(-x, y) else if (y < 0) -gcd(x, -y) else gcd(y % x, x) } def +(that: Rational) = new Rational(numer * that.denom + that.numer * denom,denom * that.denom)} numer and denom are both immutable - their values will not changed after they’ve been assigned Class definition is very similar to java Contains private method inside the class if/else statement - notice no curly braces Script-y style with no “;” to end the line

13 Type Inferencing Gives Scala the feel of being dynamically typed.
Explicit Typing var mySecondVar : String = “Bread”; var myThirdVar : Int = 13; Implicit Typing var mySecondVar = “Bread”; // Scala compiler infers this is a string var myThirdVar = 13; // Scala compiler infers this is an integer Makes it look and feel more script-y

14 Functions are Objects Can pass functions as arguments, store them in variables, and return them def sum(n: Int) : Int = if (n == 0) else n + sum(n - 1) def sum(n: Int, acc: Int) : Int = if (n == 0) acc else sum(n - 1, acc + n) Return type must be specified for recursive functions

15 Defining Functions Python has two types - functions and anonymous functions def adder(x, y) return x + y // can write an anonymous function that does the same // thing using a lambda expression adder = lambda x, y: x + y Parallels python (not so much a difference)

16 Defining Functions (cont)
Scala also has functions and anonymous functions def adder1(x: Int, y: Int): Int = { return x + y} def adder2(x: Int, y: Int) = { x + y} val adder3 = (x: Int, y: Int) => x + y // anonymous function Method declarations have the def keyword followed by the method name, optional return type, the “=” keyword, and the method body Parameter names must be followed by parameter types In general you must define function parameter types, Compiler can usually infer the return type so it can usually be omitted. exception: if you define recursive functions, ones that call themselves, you must define the return type.

17 While Loops class Rational(n: Int, d: Int) {
private def gcd(x: Int, y: Int): Int = { if (x == 0) y else if (x < 0) gcd(-x, y) else if (y < 0) -gcd(x, -y) else gcd(y % x, x) } private val g = gcd(n, d) val numer: Int = n/g val denom: Int = d/g def +(that: Rational) = new Rational(numer * that.denom + that.numer * denom,denom * that.denom)} /**Prints the sum of all numbers 1/i where i ranges from 1 to 10.*/ var i = 1 var x = new Rational(0, 1) while (i <= 10) { x += new Rational(1, i) i += 1 } println("" + x.numer + "/" + x.denom) for( a <- 1 until 10){ println( "Value of a: " + a ); }

18 Sample Code - quicksort
/** Quick sort, imperative style */ def sort(xs: Array[Int]) { def swap(i: Int, j: Int) { val t = xs(i); xs(i) = xs(j); xs(j) = t} def sort1(l: Int, r: Int) { val pivot = xs((l + r) / 2) var i = l; var j = r while (i <= j) { while (xs(i) < pivot) i += 1 while (xs(j) > pivot) j -= 1 if (i <= j) { swap(i, j) i += 1 j -= 1}} if (l < j) sort1(l, j) if (j < r) sort1(i, r)} sort1(0, xs.length - 1)} /** Quick sort, functional style */ object sort1 { def sort(a: List[Int]): List[Int] = { if (a.length < 2) a else { val pivot = a(a.length / 2) sort(a.filter(_ < pivot)) ::: a.filter(_ == pivot) ::: sort(a.filter(_ > pivot))}} def main(args: Array[String]) { val xs = List(6, 2, 8, 5, 1) println(xs) println(sort(xs))}} If/else statement main function list of type int println List declaration like python (val xs = List(6, 2, 8, 5, 1))

19 Memory Management The JVM does automatic memory management
Garbage collection is very similar to Java Scala code tends to generate more (short-lived) garbage than Java code because of the functional coding style (garbage collection is quick)

20 Real-Life Application: Twitter
One of the main application programming languages used at Twitter Much to Twitter’s infrastructure written in Scala Scala code handles billions of operations a day Chose Scala over Ruby, Java, C/C++, JavaScript Advantages of Scala Can be very idiomatic or functional - flexible It’s fast - runs on the JVM and can use Java libraries The syntax is more flexible than Java

21 Real-life Application: Coursera
Scala is Coursera’s primary serving language Why use Scala: “Scala provides a type safe language with powerful concurrency primitives on top of a mature technology platform.” Scala is much more safe with types than python Scala supports multithreading much better than python or PHP The JVM is a big advantage Concerns with Scala: Scalac (the scala compiler) is known to run very slowly There are a lot of ways to write a ton of things in Scala - hard to read someone else’s code It is possible to use unicode (such as <|***|>) Scala doesn’t have a good IDE

22 Bibliography Websites:
docs.scala-lang.org/search.html?q=abstraction tech.coursera.org/blog/2014/02/18/why-we-love-scala-at-coursera/ twitter.github.io/effectivescala/ docs.scala-lang.org/tutorials/scala-for-java-programmers.html pizzacompiler.sourceforge.net/doc/tutorial.html Books: Beginning Scala by David Pollak Programming in Scala by Martin Odersky, ‎Lex Spoon, ‎Bill Venners

23 Scala Code Everything is an expression
Everything can be grouped and nested Tail-recursive functions are guaranteed to be efficient Functions are abstracted expressions Are values Can be named or anonymous

24 Scalability Want to be able to add new libraries
Have the ability to use in small and large systems Flexible syntax Flexible types User-defined operations Higher-order functions Implicits

25 Design Goals Wanted to design a language different than Java but would connect to the Java infrastructure and the Java libraries Fully support object-oriented programming and can look kind of like Java Integrate object-oriented programming and functional programming Functional: E.g. pass functions as arguments OO: has classes, everything is an object Designed to express common programming patterns in concise, elegant, and type-safe way Statically bound types Strongly typed Can look very script-y Similar to Java, OO and functions, concise and elegant -> pull that into examples (continue to tie back to this slide) Tie how each feature connects back to a goal Could add stuff about scripting language

26 Variables Scala is statically typed and variables are statically bound
All variables and functions have types and are determined at compile time When writing code, there are few explicit type definitions because Scala can usually infer the type E.g. val x = 3 compiler infers that 'x' must be type Int as '3' is a integer literal. I If compiler cannot infer the type it will generate a type ambiguity error, and you simply add the intended type annotation. Variables in Scala can be declared as either mutable or immutable

27 Type Inferencing Type inferencing dramatically reduces the amount of typing you must do Gives a great deal more clarity to the code. Gives Scala the feel of being dynamically typed. Explicit Typing var mySecondVar : String = “Bread”; var myThirdVar : Int = 13; Implicit Typing var mySecondVar = “Bread”; // Scala compiler infers this is a string var myThirdVar = 13; // Scala compiler infers this is an integer Makes it look and feel more script-y

28 Defining Functions (cont)
In general you must define function parameter types, Compiler can usually infer the return type so it can usually be omitted. exception: if you define recursive functions, ones that call themselves, you must define the return type. Scala also has functions and anonymous functions def adder1(x: Int, y: Int): Int = { return x + y} def adder2(x: Int, y: Int) = { x = y} val adder3 = (x: Int, y: Int) => x + y // anonymous function Method declarations have the def keyword followed by the method name, optional return type, the “=” keyword, and the method body Parameter names must be followed by parameter types


Download ppt "“Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE"

Similar presentations


Ads by Google