Upload
francine-bishop
View
222
Download
2
Tags:
Embed Size (px)
Citation preview
Multiparadigm Multiparadigm Programming in ScalaProgramming in Scala
Adapted from presentation byAdapted from presentation byH. C. Cunningham and J. C. H. C. Cunningham and J. C.
Church University of Church University of MississipiMississipi
What is Multiparadigm What is Multiparadigm Programming?Programming?
Definition:Definition:A A multiparadigm programming language multiparadigm programming language provides provides ““a framework in which a framework in which programmers can work in a variety of programmers can work in a variety of styles, freely intermixing constructs from styles, freely intermixing constructs from different paradigms.different paradigms.”” [Tim Budd] [Tim Budd]
Programming paradigms:Programming paradigms: imperative versus declarative (e.g., functional, imperative versus declarative (e.g., functional,
logic)logic) other dimensions – object-oriented, component-other dimensions – object-oriented, component-
oriented, concurrency-oriented, etc.oriented, concurrency-oriented, etc.
ScalaMultiCS3180 (Prasad) 2
Why Learn Multiparadigm Why Learn Multiparadigm Programming?Programming?
Tim Budd: Tim Budd: ““Research results from the psychology of Research results from the psychology of programming indicate that expertise in programming indicate that expertise in programming is far more strongly related to programming is far more strongly related to the number of different programming styles the number of different programming styles understood by an individual than it is the understood by an individual than it is the number of yearsnumber of years of experience in of experience in programming.programming.””
The The ““goal of multiparadigm computing is to goal of multiparadigm computing is to provide ... a number of different problem-provide ... a number of different problem-solving stylessolving styles”” so that a programmer can so that a programmer can ““select a solution technique that best matches select a solution technique that best matches the characteristics of the problemthe characteristics of the problem””..
ScalaMultiCS3180 (Prasad) 3
Why Teach Multiparadigm Why Teach Multiparadigm Programming?Programming?
Contemporary imperative and object-Contemporary imperative and object-oriented languages increasingly have oriented languages increasingly have functional programming features, e.g.,functional programming features, e.g.,• higher order functions (closures)higher order functions (closures)• list comprehensionslist comprehensions
New explicitly multiparadigm (object-New explicitly multiparadigm (object-oriented/functional) languages are oriented/functional) languages are appearing, e.g.,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 platformF# on the .Net platform
ScalaMultiCS3180 (Prasad) 4
ScalaScalaProgramming language developed by Martin Programming language developed by Martin
OderskyOdersky’’s team at EPFL in Switzerlands team at EPFL in Switzerland Executes on the Java platformExecutes on the Java platform Integrates with JavaIntegrates with Java Has growing usage (e.g., Twitter, Foursquare, and Has growing usage (e.g., Twitter, Foursquare, and
Linkedin)Linkedin)Multiparadigm languageMultiparadigm language Object-oriented (with generics and mixins)Object-oriented (with generics and mixins) Functional (similar to Haskell and SML)Functional (similar to Haskell and SML) Extensible (method calls as operators, currying, Extensible (method calls as operators, currying,
closures, by-name parameters)closures, by-name parameters)• Actor-based concurrency-oriented programmingActor-based concurrency-oriented programming• Language-oriented programmingLanguage-oriented programming
Statically typed with Hindley-Milner type inferenceStatically typed with Hindley-Milner type inference
ScalaMultiCS3180 (Prasad) 5
6
Why Scala? Why Scala? (Coming from Java/C++)(Coming from Java/C++)
Runs on the JVMRuns on the JVM Can use any Java code in ScalaCan use any Java code in Scala Almost as fast as Java (within 10%)Almost as fast as Java (within 10%)
Much shorter codeMuch shorter code Odersky reports 50% reduction in most code Odersky reports 50% reduction in most code
over Javaover Java Local type inferenceLocal type inference
Fewer errorsFewer errors No Null Pointer problemsNo Null Pointer problems
More flexibilityMore flexibility As many public classes per source file as you As many public classes per source file as you
wantwant Operator overloadingOperator overloading
Scala ReferencesScala References
WebsiteWebsite http://www.scala-lang.org• Martin Odersky. Martin Odersky. Scala Tutorial for Java Scala Tutorial for Java
ProgrammersProgrammers..• Martin Odersky. Martin Odersky. Scala By ExampleScala By Example..
Martin Odersky, Lex Spoon, and Bill Martin Odersky, Lex Spoon, and Bill Venners. Venners. Programming in Scala: A Programming in Scala: A Comprehensive Step-By-Step GuideComprehensive Step-By-Step Guide, 2, 2ndnd Edition, Artima, Inc., 2010.Edition, Artima, Inc., 2010.
Books on Scala: Books on Scala: http://www.scala-lang.org/node/959http://www.scala-lang.org/node/959
ScalaMultiCS3180 (Prasad) 7
8
Scala object systemScala object system
Class-basedClass-based Single inheritance Single inheritance Can define singleton objects easily Can define singleton objects easily
(no need for static which is not (no need for static which is not really OO)really OO)
Traits, compound types, and views Traits, compound types, and views allow for more flexibilityallow for more flexibility
9
Basic ScalaBasic Scala Use Use var var to declare variables:to declare variables:
var x = 3;var x = 3;
x += 4;x += 4; Use Use val val to declare values (final vars)to declare values (final vars)
val y = 3;val y = 3;
y += 4; // errory += 4; // error Notice no types, but it is statically typedNotice no types, but it is statically typed
var x = 3;var x = 3;
x = x = ““hello worldhello world””; // error; // error Type annotations:Type annotations:
var x : Int = 3;var x : Int = 3;
10
Functional Scala Functional Scala Defining lambdas – nameless functionsDefining lambdas – nameless functions
val f = x :Int => x + 42; val f = x :Int => x + 42; f : mapping :int f : mapping :int ->-> intint
Closures! Closures! A way to haul around stateA way to haul around state
var y = 3;var y = 3;
val g = {x : Int => y += 1; x+y; }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)List(1,2,3).map(_+10).foreach(println) Filtering (and ranges!)Filtering (and ranges!)
1 to 100 filter (_ % 7 == 3) foreach (println)1 to 100 filter (_ % 7 == 3) foreach (println)
(Feels a bit like (Feels a bit like UNIX pipesUNIX pipes?)?)
Defining Hello WorldDefining Hello World
object HelloWorld { object HelloWorld { def main(args: Array[String]){def main(args: Array[String]){ println("Hey world!")println("Hey world!") }}}} Singleton object named Singleton object named HelloWorld HelloWorld (also replaces (also replaces staticstatic methods and variables) methods and variables)
Method Method main main defined (procedure)defined (procedure) Parameter Parameter argsargs of type of type Array[String]Array[String] Array Array is generic class with type parameteris generic class with type parameter
ScalaMultiCS3180 (Prasad) 11
Interpreting Hello WorldInterpreting Hello World
> scala > scala This is a Scala shell. This is a Scala shell. Type in expressions to have them evaluated. Type in expressions to have them evaluated. Type :help for more information. Type :help for more information. scala> object HelloWorld {scala> object HelloWorld { | def main(args: Array[String]) { | def main(args: Array[String]) { | println("Hey world!") | println("Hey world!") | }| } |} |} defined module HelloWorlddefined module HelloWorldscala> HelloWorld.main(null) scala> HelloWorld.main(null) Hey world! Hey world! unnamed0: Unit = () unnamed0: Unit = () scala>:qscala>:q
ScalaMultiCS3180 (Prasad) 12
Compiling & Executing Compiling & Executing Hello WorldHello World
> scalac HelloWorld.scala > scalac HelloWorld.scala
> scala HelloWorld> scala HelloWorldHey world!Hey world!
ScalaMultiCS3180 (Prasad) 13
Numbers are ObjectsNumbers are Objects
Consider expression Consider expression 1 + 2 * 3 / x1 + 2 * 3 / x
Operators are method calls (like Operators are method calls (like Smalltalk)Smalltalk)
Operator symbols are identifiersOperator symbols are identifiers
Expression above is same as Expression above is same as (1).+(((2).*(3))./(x))(1).+(((2).*(3))./(x))
ScalaMultiCS3180 (Prasad) 14
Functions are ObjectsFunctions are Objects
object Timer {object Timer { def oncePerSecond(def oncePerSecond(callback:() => Unitcallback:() => Unit){){ while (true) { while (true) { callback();callback(); Thread Thread sleepsleep 1000 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(oncePerSecond(welcomewelcome)) }}}}
ScalaMultiCS3180 (Prasad) 15
Timer ExecutionTimer Execution
scala> :l Timer.scalascala> :l Timer.scala
Loading Timer.scala...Loading Timer.scala...
defined module Timerdefined module Timer
scala> Timer.main(null)scala> Timer.main(null)
Welcome to CS3180!Welcome to CS3180!
Welcome to CS3180!Welcome to CS3180!
Welcome to CS3180!Welcome to CS3180!
……
ScalaMultiCS3180 (Prasad) 16
Anonymous FunctionsAnonymous Functions
object Timer {object Timer { def oncePerSecond(def oncePerSecond(callback:() => Unitcallback:() => Unit){){ while (true) { while (true) { callback()callback(); Thread ; Thread sleepsleep 1000 1000 }} }} def main(args: Array[String]) {def main(args: Array[String]) { oncePerSecond(oncePerSecond( () => println("Welcome to CS3180!")() => println("Welcome to CS3180!") ) ) }}}}
ScalaMultiCS3180 (Prasad) 17
ClassesClasses
class Complex(real: Double, imag: Double){class Complex(real: Double, imag: Double){ def re = realdef re = real def im = imagdef im = imag}}
Class primary constructor combined with class bodyClass primary constructor combined with class body Parameters of class private constants within classParameters of class private constants within class Parameterless methods Parameterless methods rere and and imim Return types ofReturn types of re re andand im im inferred from inferred from
expression (cannot be inferred for recursive expression (cannot be inferred for recursive functions)functions)
Thus more concise syntaxThus more concise syntax
ScalaMultiCS3180 (Prasad) 18
Method OverridingMethod Overriding// Complex.scala// Complex.scalaclass Complex(real: Double, imag: Double) {class Complex(real: Double, imag: Double) { def re = realdef re = real def im = imagdef im = imag override def toString = override def toString = re + re + (if (im < 0.0) "" else "+") (if (im < 0.0) "" else "+") + + im + ”I"im + ”I"}}
Classes extend class Classes extend class AnyRefAnyRef by default by default Methods must explicitly Methods must explicitly overrideoverride parent method parent method ifif expressions expressions
ScalaMultiCS3180 (Prasad) 19
Using Classes and ObjectsUsing Classes and Objects
scala> :load Complex.scalascala> :load Complex.scalaLoading Complex.scala...Loading Complex.scala...defined class Complexdefined class Complex
scala> val x = new Complex(1,-3) scala> val x = new Complex(1,-3) x: Complex = 1.0-3.0ix: Complex = 1.0-3.0i
scala> x.toStringscala> x.toStringres0: java.lang.String = 1.0-3.0ires0: java.lang.String = 1.0-3.0i
ScalaMultiCS3180 (Prasad) 20
Case ClassesCase Classes
abstract class Tree abstract class Tree // Expression Trees// Expression Treescase class Sum(l: Tree, r: Tree)case class Sum(l: Tree, r: Tree) extends Treeextends Treecase class Var(n: String) extends Treecase class Var(n: String) extends Treecase class Const(v: int) extends Treecase class Const(v: int) extends Tree
Cf. Algebraic data types as in functional languagesCf. Algebraic data types as in functional languages Keyword Keyword newnew not needed to create instances (objects) not needed to create instances (objects) Getters defined automatically for constructor Getters defined automatically for constructor
parametersparameters Pattern matching Pattern matching can be used to decomposecan be used to decompose
equalsequals method defined on structure of instances method defined on structure of instances
ScalaMultiCS3180 (Prasad) 21
Pattern MatchingPattern Matching
object Expressions {object Expressions { type Environ = String => Inttype 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) => vcase 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) }}
ScalaMultiCS3180 (Prasad) 22
Test Expression TreesTest 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")) }}}}
ScalaMultiCS3180 (Prasad) 23
Execute Expression TreesExecute Expression Treesscala> :load Expressions.scalascala> :load Expressions.scalaLoading Expressions.scala...Loading Expressions.scala...
……scala> Expressions.main(null)scala> Expressions.main(null)Expression: Expression: Sum(Sum(Var(x),Var(x)),Sum(Const(7),Var(y)))Sum(Sum(Var(x),Var(x)),Sum(Const(7),Var(y)))
Evaluation with x=5, y=7: 24Evaluation with x=5, y=7: 24Derivative relative to x: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: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)))
ScalaMultiCS3180 (Prasad) 24
Defs, Vals, and VarsDefs, Vals, and VarsThree types of identifier definitions:Three types of identifier definitions:
defdef defines functions with parameters; RHS defines functions with parameters; RHS expression evaluated each time calledexpression evaluated each time called
val val defines unchanging values; RHS defines unchanging values; RHS expression evaluated immediately to expression evaluated immediately to initializeinitialize
var var defines storage location whose values defines storage location whose values can be changed by assignment statements; can be changed by assignment statements; RHS expression evaluated immediately to RHS expression evaluated immediately to initializeinitialize
ScalaMultiCS3180 (Prasad) 25
TraitsTraitstrait Ord { trait Ord { // Order comparison operators// Order comparison operators def < (that: Any): Boolean def < (that: Any): Boolean // abstract// 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 methodsLike Java interfaces except can have concrete methods Can be Can be ““mixed-inmixed-in”” to class to class Note that Note that < is < is abstract; others defined with abstract; others defined with < < and and
equalsequals
ScalaMultiCS3180 (Prasad) 26
Date Class with Mixin Trait Date Class with Mixin Trait OrdOrd
class Date(y: Int, m: Int, d: Int) class Date(y: Int, m: Int, d: Int) extends Ord {extends Ord { def year = ydef year = y def month = mdef month = m def day = ddef day = d override def toString(): String = override def toString(): String = year + "-" + month + "-" + dayyear + "-" + month + "-" + day
// … need definition of < and equals// … need definition of < and equals}}
Can only extend one class or traitCan only extend one class or trait May mix-in additional classes using keywordMay mix-in additional classes using keyword with with
ScalaMultiCS3180 (Prasad) 27
Date Class Equals MethodDate Class Equals Method
override def equals(that: Any): Boolean =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 == yearo.year == year }}
isInstanceOf[T] isInstanceOf[T] checks whether object is an checks whether object is an instance of the given typeinstance of the given type T T
asInstanceOf[T] asInstanceOf[T] casts static type tocasts static type to T T if if compatible with dynamic type of objectcompatible with dynamic type of object
Value of last statement of function is returnedValue of last statement of function is returned
ScalaMultiCS3180 (Prasad) 28
Date Class < MethodDate Class < Methoddef <(that: Any): Boolean = {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))) }}
ScalaMultiCS3180 (Prasad) 29
DateTestDateTestobject 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)) }}}}
ScalaMultiCS3180 (Prasad) 30
DateTest OutputDateTest Output> scala DateTest> scala DateTestx = 1-1-2000x = 1-1-2000y = 12-31-2001y = 12-31-2001x < y: truex < y: truex > y: falsex > y: false
ScalaMultiCS3180 (Prasad) 31
Scala FunctionsScala Functions Are Are first-classfirst-class values – i.e., functions are values – i.e., functions are
objects objects Can be Can be higher-orderhigher-order – take functions as – take functions as
arguments or return them as result arguments or return them as result Can be Can be anonymousanonymous May beMay be curried curried – take arguments one at a – take arguments one at a
time, allowing time, allowing partial applicationpartial application Are often passed in aAre often passed in a closure closure – with – with
references to free variables they maninpulatereferences to free variables they maninpulate Provide ability to build powerful Provide ability to build powerful librarieslibraries of of
higher-order functionshigher-order functions
ScalaMultiCS3180 (Prasad) 32
Curried FunctionsCurried Functionsscala> def addscala> def add(x: Int, y: Int(x: Int, y: Int) = x + y) = x + yadd: (Int,Int)Intadd: (Int,Int)Intscala> add(1,3)scala> add(1,3)res0: Int = 4res0: Int = 4
scala> def addcscala> def addc(x: Int)(y: Int(x: Int)(y: Int) = x + y) = x + yaddc: (Int)(Int)Intaddc: (Int)(Int)Intscala> addcscala> addc(1)(3)(1)(3)res1: Int = 4res1: Int = 4
ScalaMultiCS3180 (Prasad) 33
Partial ApplicationPartial Applicationscala> def addcscala> def addc(x: Int)(y: Int(x: Int)(y: Int) = x + y) = x + yaddc: (Int)(Int)Intaddc: (Int)(Int)Int
scala> val z = addcscala> val z = addc(1) _(1) _z: (Int) => Int = <function>z: (Int) => Int = <function>
scala> scala> z(3z(3) ) res2: Int = 4res2: Int = 4
ScalaMultiCS3180 (Prasad) 34
ClosuresClosuresscala> val inc = 10scala> val inc = 10
inc: Int = 10inc: Int = 10
scala> def incre(x: Int) = x + scala> def incre(x: Int) = x + incinc
incre: (Int)Intincre: (Int)Int
scala> def app(y: Int, g: (Int=>Int)) = g(y)scala> def app(y: Int, g: (Int=>Int)) = g(y)
app: (Int,(Int) => Int)Intapp: (Int,(Int) => Int)Int
scala> app(13,incre)scala> app(13,incre)
res0: Int = 23res0: Int = 23
ScalaMultiCS3180 (Prasad) 35
Using List MapUsing List Map
scala> val xs = List(3,4,5)scala> val xs = List(3,4,5)xs: List[Int] = List(3, 4, 5)xs: List[Int] = List(3, 4, 5)
scala> val triples = xs.map(x => 3*x)scala> val triples = xs.map(x => 3*x)triples: List[Int] = List(9, 12, 15)triples: List[Int] = List(9, 12, 15)
scala> scala> val evens = xs.filter(x => x%2==0)val evens = xs.filter(x => x%2==0)
evens: List[Int] = List(4)evens: List[Int] = List(4)
ScalaMultiCS3180 (Prasad) 37
Other Higher Order List Other Higher Order List MethodsMethods
flatMapflatMap
foldLeft, foldRightfoldLeft, foldRight
reduceLeft, reduceRightreduceLeft, reduceRight
takeWhile, dropWhiletakeWhile, dropWhile
span, breakspan, break
foreachforeach
ScalaMultiCS3180 (Prasad) 39
For ComprehensionsFor Comprehensionsscala> for(i <- 1 to 30; scala> 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: res0: scala.collection.immutable.IndexedSeq[(Int, Int)] scala.collection.immutable.IndexedSeq[(Int, Int)] = = Vector((2,2), (3,3), (4,2), (5,5), (6,2),Vector((2,2), (3,3), (4,2), (5,5), (6,2),
(6,3), (7,7), (8,2), (9,3), (10,2), (10,5), (6,3), (7,7), (8,2), (9,3), (10,2), (10,5), (12,2), (12,3), (14,2), (14,7), (15,3), (15,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), (16,2),(18,2), (18,3), (20,2), (20,5), (21,3), (21,7), (22,2), (24,2), (24,3), (25,5), (26,2), (21,7), (22,2), (24,2), (24,3), (25,5), (26,2), (27,3), (28,2), (28,7), (30,2), (30,3), (30,5))(27,3), (28,2), (28,7), (30,2), (30,3), (30,5))
ScalaMultiCS3180 (Prasad) 40
Scala class hierarchyScala class hierarchy
Actors in ScalaActors in Scala
ScalaMultiCS3180 (Prasad) 43
MotivationMotivation
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 Concurrent processes should pass messages to other processes rather than messages to other processes rather than share memory.share memory.
Erlang's processes are part of the Erlang's processes are part of the language.language.
Scala's actors are part of the library.Scala's actors are part of the library.ScalaMultiCS3180 (Prasad) 44
ActorsActors
Actors act independent of other Actors act independent of other actors.actors.
Actors have mailboxes.Actors have mailboxes. Actors communicate by sending Actors communicate by sending
messages to other actors.messages to other actors. Actors will check their mailbox and Actors will check their mailbox and
react to their messages.react to their messages.
ScalaMultiCS3180 (Prasad) 45
Message in a BottleMessage in a Bottle
Any object can be sent to an ActorAny object can be sent to an Actor
case object myMessageObject
...
myActor ! myMessageObject
ScalaMultiCS3180 (Prasad) 46
Please Mr. PostmanPlease Mr. Postman
How urgent is it?How urgent is it? reactreact: I need it now!: I need it now! receiveWithinreceiveWithin: I need it soon!: I need it soon! receivereceive: I'll wait.: I'll wait.
All three methods will perform All three methods will perform pattern matching on the objects pattern matching on the objects received.received.
ScalaMultiCS3180 (Prasad) 47
OveractingOveractingimport scala.actors._import scala.actors._
object SillyActor extends Actor {object SillyActor extends Actor {
def act() { def act() { // Defines how our actor acts// 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() SillyActor.start() // Begins acting// Begins acting
ScalaMultiCS3180 (Prasad) 48
Vegetable LauncherVegetable Launchercase object Tomatocase object Tomato
case object Lettucecase object Lettuce
object VegetableLauncher extends Actor {object VegetableLauncher extends Actor {
def act() {def act() {
for (i <- 1 to 5) {for (i <- 1 to 5) {
VegetableCatcher ! Tomato VegetableCatcher ! Tomato // Send it!// Send it!
Thread.sleep(1000)Thread.sleep(1000)
VegetableCatcher ! Lettuce VegetableCatcher ! Lettuce // Send it!// Send it!
Thread.sleep(1000)Thread.sleep(1000)
}}
}}
}}
ScalaMultiCS3180 (Prasad) 49
Vegetable CatcherVegetable Catcherobject VegetableCatcher extends Actor {object VegetableCatcher extends Actor {
def act() {def act() {
loop {loop {
react { react { // Non-blocking call// 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!")
}}
}}
}}
}}
ScalaMultiCS3180 (Prasad) 50
Lights, Camera, ...Lights, Camera, ...VegetableLauncher.start()VegetableLauncher.start()
VegetableCatcher.start()VegetableCatcher.start()
SillyActor.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!
ScalaMultiCS3180 (Prasad) 51