“Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

More about functions Plus a few random things. 2 Tail recursion A function is said to be tail recursive if the recursive call is the very last thing it.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
CS 330 Programming Languages 10 / 16 / 2008 Instructor: Michael Eckmann.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
10/16/2015IT 3271 All about binding n Variables are bound (dynamically) to values n values must be stored somewhere in the memory. Memory Locations for.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Basic Semantics Associating meaning with language entities.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python Functions.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Peyman Dodangeh Sharif University of Technology Spring 2014.
CS 330 Programming Languages 10 / 23 / 2007 Instructor: Michael Eckmann.
Review A program is… a set of instructions that tell a computer what to do. Programs can also be called… software. Hardware refers to… the physical components.
ISBN Chapter 12 Support for Object-Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Heath Carroll Bill Hanczaryk Rich Porter.  A Theory of Type Polymorphism in Programming ◦ Robin Milner (1977)  Milner credited with introducing the.
CS314 – Section 5 Recitation 9
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Object Lifetime and Pointers
What do you need to know about a new language?
Functions + Overloading + Scope
Data Types In Text: Chapter 6.
Topic: Classes and Objects
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Prof: Dr. Shu-Ching Chen TA: Samira Pouyanfar Spring 2017
Chapter 7 User-Defined Methods.
Intro to ETEC Java.
Chapter 6 – Data Types CSCE 343.
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
Java Primer 1: Types, Classes and Operators
Object Oriented Programming
Engineering Innovation Center
Advanced Programming Behnam Hatami Fall 2017.
Functional Programming with Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
FP Foundations, Scheme In Text: Chapter 14.
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
Programs and Classes A program is made up from classes
Introduction to Data Structure
Java Programming Language
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Java Basics Data Types in Java.
The C Language: Intro.
Java’s Central Casting
Lecture 10 Concepts of Programming Languages
Classes and Objects Object Creation
Lecture 7: Types (Revised based on the Tucker’s slides) 10/4/2019
SPL – PS2 C++ Memory Handling.
Presentation transcript:

“Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE Scalable Language “Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE http://www.slideshare.net/Odersky/scala-the-simple-parts?related=1 http://www.scala-lang.org/files/archive/spec/2.11/ http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html http://www.simplyscala.com/

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

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

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

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)

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

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

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

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.

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

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

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

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

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

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)

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.

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 ); }

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))

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)

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 http://twitter.github.io/effectivescala/, https://www.redfin.com/devblog/2010/05/how_and_why_twitter_uses_scala.html#.VSsKEJTF_H4

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 https://tech.coursera.org/blog/2014/02/18/why-we-love-scala-at-coursera/

Bibliography Websites: www.tutorialspoint.com/scala/scala_functions.htm 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/ www.redfin.com/devblog/2010/05/how_and_why_twitter_uses_scala.html#.VSsKEJTF_H4 www.slideshare.net/Odersky/scala-the-simple-parts?related=1 www.scala-lang.org/files/archive/spec/2.11/ docs.scala-lang.org/tutorials/scala-for-java-programmers.html www.simplyscala.com/ pizzacompiler.sourceforge.net/doc/tutorial.html Books: Beginning Scala by David Pollak Programming in Scala by Martin Odersky, ‎Lex Spoon, ‎Bill Venners

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

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

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

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

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

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