Multiparadigm Programming in Scala Adapted from presentation by H. C. Cunningham and J. C. Church University of Mississipi.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
INF 212 ANALYSIS OF PROG. LANGS Type Systems Instructors: Crista Lopes Copyright © Instructors.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
6/10/2015Martin Odersky, LAMP, EPFL1 Programming Language Abstractions for Semi-Structured Data Martin Odersky Sebastian Maneth Burak Emir EPFL.
Road Map Introduction to object oriented programming. Classes
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Chapter 10 Classes Continued
OOP Languages: Java vs C++
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Imperative Programming
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
The Scala Programming Language presented by Donna Malayeri.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 1 - Introduction
Scala Overview Brandon Clopton CSCI 431. Scala fuses object-oriented and functional programming in a statically typed programming language. It is aimed.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Introduction to Scala Lecture 1 CMSC 331 SD Vick.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
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.
- Neeraj Chandra.  It’s language written by by Martin Odersky at EPFL  It’s language written by by Martin Odersky at EPFL (École Polytechnique Fédérale.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
The Scala API. Scala has a reputation of being a difficult language Some people feel that Scala is beyond what the average programmer can master Others.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Classes and Objects and Traits And Other Miscellany 25-Jan-16.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Sequences and for loops. Simple for loops A for loop is used to do something with every element of a sequence scala> for (i
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Introduction to Functional Programming Part 1 – The Basic Concepts Winter Young
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
“Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE
Functional Programming
Type Checking and Type Inference
CS1022 Computer Programming & Principles
Multiparadigm Programming in Scala
Introduction to Scala SD Vick 1.
Java Primer 1: Types, Classes and Operators
Functional Programming with Java
Java Programming Language
FP Foundations, Scheme In Text: Chapter 14.
The Scala API.
Classes and Objects Object Creation
Chengyu Sun California State University, Los Angeles
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Multiparadigm Programming in Scala Adapted from presentation by H. C. Cunningham and J. C. Church University of Mississipi

What is Multiparadigm Programming? Definition: A multiparadigm programming language provides “ a framework in which programmers can work in a variety of styles, freely intermixing constructs from different paradigms. ” [Tim Budd] Programming paradigms:  imperative versus declarative (e.g., functional, logic)  other dimensions – object-oriented, component-oriented, concurrency-oriented, etc. ScalaMulti CS3180 (Prasad) 2

Why Learn Multiparadigm Programming? Tim Budd: “ Research results from the psychology of programming indicate that expertise in programming is far more strongly related to the number of different programming styles understood by an individual than it is the number of years of experience in programming. ” The “ goal of multiparadigm computing is to provide... a number of different problem-solving styles ” so that a programmer can “ select a solution technique that best matches the characteristics of the problem ”. ScalaMulti CS3180 (Prasad) 3

Why Teach Multiparadigm Programming?  Contemporary imperative and object-oriented languages increasingly have functional programming features, e.g., higher order functions (closures) higher order functions (closures) list comprehensions list comprehensions  New explicitly multiparadigm (object- oriented/functional) languages are appearing, e.g., Scala on the Java platform (and.Net in future) Scala on the Java platform (and.Net in future) F# on the.Net platform F# on the.Net platform ScalaMulti CS3180 (Prasad) 4

Scala Programming language developed by Martin Odersky ’ s team at EPFL in Switzerland  Executes on the Java platform  Integrates with Java  Has growing usage (e.g., Twitter, Foursquare, and Linkedin) Multiparadigm language  Object-oriented (with generics and mixins)  Functional (similar to Haskell and SML)  Extensible (method calls as operators, currying, closures, by- name parameters) Actor-based concurrency-oriented programming Actor-based concurrency-oriented programming Language-oriented programming Language-oriented programming  Statically typed with Hindley-Milner type inference ScalaMulti CS3180 (Prasad) 5

6 Why Scala? (Coming from Java/C++) Runs on the JVM Runs on the JVM Can use any Java code in Scala Can use any Java code in Scala Almost as fast as Java (within 10%) Almost as fast as Java (within 10%) Much shorter code Much shorter code Odersky reports 50% reduction in most code over Java Odersky reports 50% reduction in most code over Java Local type inference Local type inference Fewer errors Fewer errors No Null Pointer problems No Null Pointer problems More flexibility More flexibility As many public classes per source file as you want As many public classes per source file as you want Operator overloading Operator overloading

Scala References  Website Martin Odersky. Scala Tutorial for Java Programmers. Martin Odersky. Scala Tutorial for Java Programmers. Martin Odersky. Scala By Example. Martin Odersky. Scala By Example.  Martin Odersky, Lex Spoon, and Bill Venners. Programming in Scala: A Comprehensive Step-By-Step Guide, 2 nd Edition, Artima, Inc.,  Books on Scala: ScalaMulti CS3180 (Prasad) 7

8 Scala object system Class-based Class-based Single inheritance Single inheritance Can define singleton objects easily (no need for static which is not really OO) Can define singleton objects easily (no need for static which is not really OO) Traits, compound types, and views allow for more flexibility Traits, compound types, and views allow for more flexibility

9 Basic Scala Use var to declare variables: Use var to declare variables: var x = 3; x += 4; Use val to declare values (final vars) Use val to declare values (final vars) val y = 3; y += 4; // error Notice no types, but it is statically typed Notice no types, but it is statically typed var x = 3; x = “hello world”; // error Type annotations: Type annotations: var x : Int = 3;

10 Functional Scala Defining lambdas – nameless functions Defining lambdas – nameless functions val f = x :Int => x + 42; f : mapping :int -> int Closures! A way to haul around state Closures! A way to haul around state var y = 3; val g = {x : Int => y += 1; x+y; } Maps (and a cool way to do some functions) Maps (and a cool way to do some functions)List(1,2,3).map(_+10).foreach(println) Filtering (and ranges!) Filtering (and ranges!) 1 to 100 filter (_ % 7 == 3) foreach (println) (Feels a bit like UNIX pipes?) (Feels a bit like UNIX pipes?)

Defining Hello World object HelloWorld { def main(args: Array[String]){ def main(args: Array[String]){ println("Hey world!") println("Hey world!") }}  Singleton object named HelloWorld (also replaces static methods and variables)  Method main defined (procedure)  Parameter args of type Array[String]  Array is generic class with type parameter ScalaMulti CS3180 (Prasad) 11

Interpreting Hello World > scala This is a Scala shell. Type in expressions to have them evaluated. Type :help for more information. scala> object HelloWorld { | def main(args: Array[String]) { | def main(args: Array[String]) { | println("Hey world!") | println("Hey world!") | } | } defined module HelloWorld scala> HelloWorld.main(null) Hey world! unnamed0: Unit = () scala>:q ScalaMulti CS3180 (Prasad) 12

Compiling & Executing Hello World > scalac HelloWorld.scala > scala HelloWorld Hey world! ScalaMulti CS3180 (Prasad) 13

Numbers are Objects  Consider expression * 3 / x  Operators are method calls (like Smalltalk)  Operator symbols are identifiers  Expression above is same as (1).+(((2).*(3))./(x)) ScalaMulti CS3180 (Prasad) 14

Functions are Objects object Timer { def oncePerSecond(callback:() => Unit){ def oncePerSecond(callback:() => Unit){ while (true) { while (true) { callback(); Thread sleep 1000 callback(); Thread sleep 1000 } // 1-arg method sleep used as operator } // 1-arg method sleep used as operator } def welcome() { def welcome() { println("Welcome to CS3180!") println("Welcome to CS3180!") } def main(args: Array[String]) { def main(args: Array[String]) { oncePerSecond(welcome) oncePerSecond(welcome) }} ScalaMulti CS3180 (Prasad) 15

Timer Execution scala> :l Timer.scala Loading Timer.scala... defined module Timer scala> Timer.main(null) Welcome to CS3180! … ScalaMulti CS3180 (Prasad) 16

Anonymous Functions object Timer { def oncePerSecond(callback:() => Unit){ def oncePerSecond(callback:() => Unit){ while (true) { while (true) { callback(); Thread sleep 1000 callback(); Thread sleep 1000 } } def main(args: Array[String]) { def main(args: Array[String]) { oncePerSecond( oncePerSecond( () => println("Welcome to CS3180!") ) () => println("Welcome to CS3180!") ) }} ScalaMulti CS3180 (Prasad) 17

Classes class Complex(real: Double, imag: Double){ def re = real def re = real def im = imag def im = imag}  Class primary constructor combined with class body  Parameters of class private constants within class  Parameterless methods re and im  Return types of re and im inferred from expression (cannot be inferred for recursive functions)  Thus more concise syntax ScalaMulti CS3180 (Prasad) 18

Method Overriding // Complex.scala class Complex(real: Double, imag: Double) { def re = real def re = real def im = imag def im = imag override def toString = override def toString = re + (if (im < 0.0) "" else "+") + re + (if (im < 0.0) "" else "+") + im + ”I" im + ”I"}  Classes extend class AnyRef by default  Methods must explicitly override parent method  if expressions ScalaMulti CS3180 (Prasad) 19

Using Classes and Objects scala> :load Complex.scala Loading Complex.scala... defined class Complex scala> val x = new Complex(1,-3) x: Complex = i scala> x.toString res0: java.lang.String = i ScalaMulti CS3180 (Prasad) 20

Case Classes abstract class Tree // Expression Trees case class Sum(l: Tree, r: Tree) extends Tree extends Tree case class Var(n: String) extends Tree case class Const(v: int) extends Tree  Cf. Algebraic data types as in functional languages  Keyword new not needed to create instances (objects)  Getters defined automatically for constructor parameters  Pattern matching can be used to decompose  equals method defined on structure of instances ScalaMulti CS3180 (Prasad) 21

Pattern Matching object Expressions { type Environ = String => Int type Environ = String => Int def eval(t: Tree, env: Environ): Int = t match { def eval(t: Tree, env: Environ): Int = t match { case Sum(l,r) => eval(l,env) + eval(r,env) case Sum(l,r) => eval(l,env) + eval(r,env) case Var(n) => env(n) case Var(n) => env(n) case Const(v) => v case Const(v) => v } def derive(t: Tree, v: String): Tree = t match { def derive(t: Tree, v: String): Tree = t match { case Sum(l,r) => Sum(derive(l,v), case Sum(l,r) => Sum(derive(l,v), derive(r,v)) derive(r,v)) case Var(n) if (v == n) => Const(1) case Var(n) if (v == n) => Const(1) case _ => Const(0) case _ => Const(0) } ScalaMulti CS3180 (Prasad) 22

Test Expression Trees def main(args: Array[String]) { def main(args: Array[String]) { val exp: Tree = val exp: Tree = Sum(Sum(Var("x"),Var("x")), Sum(Sum(Var("x"),Var("x")), Sum(Const(7),Var("y"))) Sum(Const(7),Var("y"))) val env: Environ = val env: Environ = { case "x" => 5 case "y" => 7 } { case "x" => 5 case "y" => 7 } println("Expression: " + exp) println("Expression: " + exp) println("Evaluation with x=5, y=7: " + println("Evaluation with x=5, y=7: " + eval(exp,env)) eval(exp,env)) println("Derivative relative to x:\n " + println("Derivative relative to x:\n " + derive(exp, "x")) derive(exp, "x")) println("Derivative relative to y:\n " + println("Derivative relative to y:\n " + derive(exp, "y")) derive(exp, "y")) }} ScalaMulti CS3180 (Prasad) 23

Execute Expression Trees scala> :load Expressions.scala Loading Expressions.scala... … scala> Expressions.main(null) Expression: Sum(Sum(Var(x),Var(x)),Sum(Const(7),Var(y))) Evaluation with x=5, y=7: 24 Derivative relative to x: Sum(Sum(Const(1),Const(1)),Sum(Const(0),Const(0))) Sum(Sum(Const(1),Const(1)),Sum(Const(0),Const(0))) Derivative relative to y: Sum(Sum(Const(0),Const(0)),Sum(Const(0),Const(1))) Sum(Sum(Const(0),Const(0)),Sum(Const(0),Const(1))) ScalaMulti CS3180 (Prasad) 24

Defs, Vals, and Vars Three types of identifier definitions: def defines functions with parameters; RHS expression evaluated each time called val defines unchanging values; RHS expression evaluated immediately to initialize var defines storage location whose values can be changed by assignment statements; RHS expression evaluated immediately to initialize ScalaMulti CS3180 (Prasad) 25

Traits trait Ord { // Order comparison operators def < (that: Any): Boolean // abstract def < (that: Any): Boolean // abstract def <=(that: Any): Boolean = def <=(that: Any): Boolean = (this < that) || (this == that) (this < that) || (this == that) def > (that: Any): Boolean = def > (that: Any): Boolean = !(this <= that) !(this <= that) def >=(that: Any): Boolean = def >=(that: Any): Boolean = !(this < that) !(this < that)}  Like Java interfaces except can have concrete methods  Can be “ mixed-in ” to class  Note that < is abstract; others defined with < and equals ScalaMulti CS3180 (Prasad) 26

Date Class with Mixin Trait Ord class Date(y: Int, m: Int, d: Int) extends Ord { extends Ord { def year = y def year = y def month = m def month = m def day = d def day = d override def toString(): String = override def toString(): String = year + "-" + month + "-" + day year + "-" + month + "-" + day // … need definition of < and equals // … need definition of < and equals}  Can only extend one class or trait  May mix-in additional classes using keyword with ScalaMulti CS3180 (Prasad) 27

Date Class Equals Method override def equals(that: Any): Boolean = that.isInstanceOf[Date] && { that.isInstanceOf[Date] && { val o = that.asInstanceOf[Date] val o = that.asInstanceOf[Date] o.day == day && o.month == month && o.day == day && o.month == month && o.year == year o.year == year }  isInstanceOf[T] checks whether object is an instance of the given type T  asInstanceOf[T] casts static type to T if compatible with dynamic type of object  Value of last statement of function is returned ScalaMulti CS3180 (Prasad) 28

Date Class < Method def <(that: Any): Boolean = { if (!that.isInstanceOf[Date]) if (!that.isInstanceOf[Date]) error("Cannot compare " + that + error("Cannot compare " + that + " and a Date") " and a Date") val o = that.asInstanceOf[Date] val o = that.asInstanceOf[Date] (year < o.year) || (year < o.year) || (year == o.year && (year == o.year && (month < o.month || (month < o.month || (month == o.month && day < o.day))) (month == o.month && day < o.day))) } ScalaMulti CS3180 (Prasad) 29

DateTest object DateTest { def main(args: Array[String]) { def main(args: Array[String]) { val x = new Date(1,1,2000) val x = new Date(1,1,2000) val y = new Date(12,31,2001) val y = new Date(12,31,2001) println("x = " + x) println("x = " + x) println("y = " + y) println("y = " + y) println("x < y: " + (x<y)) println("x < y: " + (x<y)) println("x > y: " + (x>y)) println("x > y: " + (x>y)) }} ScalaMulti CS3180 (Prasad) 30

DateTest Output > scala DateTest x = y = x < y: true x > y: false ScalaMulti CS3180 (Prasad) 31

Scala Functions  Are first-class values – i.e., functions are objects  Can be higher-order – take functions as arguments or return them as result  Can be anonymous  May be curried – take arguments one at a time, allowing partial application  Are often passed in a closure – with references to free variables they maninpulate  Provide ability to build powerful libraries of higher- order functions ScalaMulti CS3180 (Prasad) 32

Curried Functions scala> def add(x: Int, y: Int) = x + y add: (Int,Int)Int scala> add(1,3) res0: Int = 4 scala> def addc(x: Int)(y: Int) = x + y addc: (Int)(Int)Int scala> addc(1)(3) res1: Int = 4 ScalaMulti CS3180 (Prasad) 33

Partial Application scala> def addc(x: Int)(y: Int) = x + y addc: (Int)(Int)Int scala> val z = addc(1) _ z: (Int) => Int = z: (Int) => Int = scala> z(3) res2: Int = 4 ScalaMulti CS3180 (Prasad) 34

Closures scala> val inc = 10 inc: Int = 10 scala> def incre(x: Int) = x + inc incre: (Int)Int scala> def app(y: Int, g: (Int=>Int)) = g(y) app: (Int,(Int) => Int)Int scala> app(13,incre) res0: Int = 23 ScalaMulti CS3180 (Prasad) 35

List Processing // Not actual Scala API code abstract class List[+A]{ … def map[B](f: (A)=> B): List[B] = def map[B](f: (A)=> B): List[B] = this match { this match { case Nil => this case Nil => this case x::xs => f(x)::xs.map(f) case x::xs => f(x)::xs.map(f) } … } …} case object Nil extends List[Nothing] case final class ::[B] (private hd: B, val tl: List[B]) (private hd: B, val tl: List[B]) extends List[B] extends List[B] ScalaMulti CS3180 (Prasad) 36

Using List Map scala> val xs = List(3,4,5) xs: List[Int] = List(3, 4, 5) scala> val triples = xs.map(x => 3*x) triples: List[Int] = List(9, 12, 15) scala> val evens = xs.filter(x => x%2==0) evens: List[Int] = List(4) ScalaMulti CS3180 (Prasad) 37

More List Processing // Not actual Scala API code abstract class List[+A]{ … def filter(p: (A) => Boolean): List[A] = def filter(p: (A) => Boolean): List[A] = this match { this match { case Nil => this case Nil => this case x::xs => case x::xs => if (p(x)) x::xs.filter(p) if (p(x)) x::xs.filter(p) else xs.filter(p) else xs.filter(p) } …} ScalaMulti CS3180 (Prasad) 38

Other Higher Order List Methods  flatMap  foldLeft, foldRight  reduceLeft, reduceRight  takeWhile, dropWhile  span, break  foreach ScalaMulti CS3180 (Prasad) 39

For Comprehensions scala> for(i for(i <- 1 to 30; | j <- List(2,3,5,7); | j <- List(2,3,5,7); | if i % j == 0) yield (i,j) | if i % j == 0) yield (i,j) res0: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((2,2), (3,3), (4,2), (5,5), (6,2), res0: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((2,2), (3,3), (4,2), (5,5), (6,2), (6,3), (7,7), (8,2), (9,3), (10,2), (10,5), (12,2), (12,3), (14,2), (14,7), (15,3), (15,5), (16,2),(18,2), (18,3), (20,2), (20,5), (21,3), (21,7), (22,2), (24,2), (24,3), (25,5), (26,2), (27,3), (28,2), (28,7), (30,2), (30,3), (30,5)) ScalaMulti CS3180 (Prasad) 40

41 object TargetTest with Application { def loopWhile(def cond: Boolean)(def body: Unit): Unit = def loopWhile(def cond: Boolean)(def body: Unit): Unit = if (cond) { if (cond) { body; body; loopWhile(cond)(body); loopWhile(cond)(body); } var i = 10; var i = 10; loopWhile (i > 0) { loopWhile (i > 0) { Console.println(i); Console.println(i); i = i – 1 // Note: var/val i = i – 1 // Note: var/val }} }} Example Defining New Control Structure Define loopWhile method Use it with nice syntax

Scala class hierarchy

Actors in Scala ScalaMulti CS3180 (Prasad) 43

Motivation Concurrency is hard! Concurrency is hard! Real World is parallel and distributed. Real World is parallel and distributed. Erlang's notion of a process: Erlang's notion of a process: Concurrent processes should pass messages to other processes rather than share memory. Concurrent processes should pass messages to other processes rather than share memory. Erlang's processes are part of the language. Erlang's processes are part of the language. Scala's actors are part of the library. Scala's actors are part of the library. ScalaMulti CS3180 (Prasad) 44

Actors Actors act independent of other actors. Actors act independent of other actors. Actors have mailboxes. Actors have mailboxes. Actors communicate by sending messages to other actors. Actors communicate by sending messages to other actors. Actors will check their mailbox and react to their messages. Actors will check their mailbox and react to their messages. ScalaMulti CS3180 (Prasad) 45

Message in a Bottle Any object can be sent to an Actor Any object can be sent to an Actor case object myMessageObject... myActor ! myMessageObject ScalaMulti CS3180 (Prasad) 46

Please Mr. Postman How urgent is it? How urgent is it? react: I need it now! react: I need it now! receiveWithin: I need it soon! receiveWithin: I need it soon! receive: I'll wait. receive: I'll wait. All three methods will perform pattern matching on the objects received. All three methods will perform pattern matching on the objects received. ScalaMulti CS3180 (Prasad) 47

Overacting import scala.actors._ object SillyActor extends Actor { def act() { // Defines how our actor acts def act() { // Defines how our actor acts for (i <- 1 to 5) { for (i <- 1 to 5) { println(“I'm acting!”) println(“I'm acting!”) Thread.sleep(1000) Thread.sleep(1000) } }}... SillyActor.start() // Begins acting ScalaMulti CS3180 (Prasad) 48

Vegetable Launcher case object Tomato case object Lettuce object VegetableLauncher extends Actor { def act() { def act() { for (i <- 1 to 5) { for (i <- 1 to 5) { VegetableCatcher ! Tomato // Send it! VegetableCatcher ! Tomato // Send it! Thread.sleep(1000) Thread.sleep(1000) VegetableCatcher ! Lettuce // Send it! VegetableCatcher ! Lettuce // Send it! Thread.sleep(1000) Thread.sleep(1000) } }} ScalaMulti CS3180 (Prasad) 49

Vegetable Catcher object VegetableCatcher extends Actor { def act() { def act() { loop { loop { react { // Non-blocking call react { // Non-blocking call // Pattern Matching // Pattern Matching case Lettuce => case Lettuce => println("I caught a lettuce!") println("I caught a lettuce!") case Tomato => case Tomato => println("I caught a tomato!") println("I caught a tomato!") } } }} ScalaMulti CS3180 (Prasad) 50

Lights, Camera,... VegetableLauncher.start()VegetableCatcher.start()SillyActor.start() I'm acting! I caught a tomato! I'm acting! I caught a lettuce! I'm acting! I caught a tomato! I'm acting! I caught a lettuce! I'm acting! I caught a tomato! I caught a lettuce! I caught a tomato! I caught a lettuce! I caught a tomato! I caught a lettuce! ScalaMulti CS3180 (Prasad) 51

Dining Philosophers Five philosophers compete for limited resources. Five philosophers compete for limited resources. Deadlocks are possible. Deadlocks are possible. Solution implemented with a waiter. Solution implemented with a waiter. 11 actors total: 11 actors total: 5 philosophers 5 philosophers 5 chopsticks (A mutex actor) ‏ 5 chopsticks (A mutex actor) ‏ 1 waiter (A singleton object actor) ‏ 1 waiter (A singleton object actor) ‏ ScalaMulti CS3180 (Prasad) 52

The waiter only allows four to sit. After that, names are on the wait list. The waiter only allows four to sit. After that, names are on the wait list. Philosophers must still wait for chopsticks after sitting. Philosophers must still wait for chopsticks after sitting. ScalaMulti CS3180 (Prasad) 53

Six Messages import scala.actors._ import scala.actors.Actor._ import java.util.Random // Philosopher and Waiter communication case object NeedToEat case object HaveASeat case object DoneEating // Philosopher and Chopstick communication case object NeedChopstick case object HeresAChopstick case object GiveBackChopstick ScalaMulti CS3180 (Prasad) 54

Chopstick “Mutex” class Chopstick extends Actor { def act() { def act() { loop { loop { react { react { case NeedChopstick => case NeedChopstick => sender ! HeresAChopstick sender ! HeresAChopstick receive { receive { case GiveBackChopstick => case GiveBackChopstick => 1 } } } }} ScalaMulti CS3180 (Prasad) 55