Multiparadigm Programming in Scala Adapted from presentation by H.. Definition: A multiparadigm programming language provides “ a a framework framework in in which which programmers ca
Trang 1Multiparadigm Programming
in Scala
Adapted from presentation by
H C Cunningham and J C Church
University of Mississipi
Trang 2What is Multiparadigm
Programming?
Definition:
A multiparadigm programming language
provides “ a a framework framework in in which which programmers can work in a variety of styles, freely intermixing constructs from different paradigms ” [Tim Budd]
Trang 3component-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
number of years of of experience experience in 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 ” .
Trang 4Why Teach Multiparadigm
Programming?
Contemporary imperative and oriented languages increasingly have functional programming features, e.g.,
object-• higher order functions (closures)
Trang 5Programming 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
• Language-oriented programming
Statically typed with Hindley-Milner type inference
Trang 6Why Scala?
(Coming from Java/C++)
Runs on the JVM
Can use any Java code in Scala
Almost as fast as Java (within 10%)
Much shorter code
Odersky reports 50% reduction in most code over Java
Local type inference
Trang 7Scala References
Website http://www.scala-lang.org
• Martin Odersky Scala Tutorial for Java Programmers
• 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., 2010.
Books on Scala:
http://www.scala-lang.org/node/959
Trang 8Scala object system
Trang 10Functional Scala
Defining lambdas – nameless functions
int
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) List(1,2,3).map(_+10).foreach(println)
Filtering (and ranges!)
1 to 100 filter (_ % 7 == 3) foreach (println)
(Feels a bit like UNIX pipes?)
Trang 11Defining Hello 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
Trang 12Interpreting 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]) {
Trang 13Compiling & Executing Hello World
> scalac HelloWorld.scala
> scala HelloWorld
Hey world!
Trang 14Numbers are Objects
Consider expression
1 + 2 * 3 / x
Operators are method calls (like
Smalltalk)
Operator symbols are identifiers
Expression above is same as
(1).+(((2).*(3))./(x))
Trang 15Functions are Objects
object Timer {
def oncePerSecond(callback:() => Unit){
while (true) {
callback(); Thread sleep 1000
} // 1-arg method sleep used as operator
Trang 17}
Trang 18(cannot be inferred for recursive functions)
Trang 19override def toString =
re + (if (im < 0.0) "" else "+") +
im + ”I"
}
Classes extend class AnyRef by default
Methods must explicitly override parent
method
Trang 20Using Classes and Objects
scala> :load Complex.scala
Loading Complex.scala
defined class Complex
scala> val x = new Complex(1,-3)
x: Complex = 1.0-3.0i
scala> x.toString
res0: java.lang.String = 1.0-3.0i
Trang 21Case Classes
abstract class Tree // Expression Trees
case class Sum(l: Tree, r: Tree)
extends Tree
case class Var(n: String) extends Tree
case class Const(v: int) extends Tree
(objects)
parameters
Trang 22Pattern Matching
object Expressions {
type Environ = String => Int
def eval(t: Tree, env: Environ): Int = t match { case Sum(l,r) => eval(l,env) + eval(r,env)
case Var(n) => env(n)
Trang 23Test Expression Trees
def main(args: Array[String]) {
val exp: Tree =
Sum(Sum(Var("x"),Var("x")), Sum(Const(7),Var("y")))
val env: Environ =
{ case "x" => 5 case "y" => 7 }
Trang 24Execute Expression Trees
scala> :load Expressions.scala
Sum(Sum(Const(0),Const(0)),Sum(Const(0),Const(1)))
Trang 25Defs, 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
Trang 26trait Ord { // Order comparison operators
def < (that: Any): Boolean // abstract
def <=(that: Any): Boolean =
(this < that) || (this == that)
def > (that: Any): Boolean =
equals
Trang 27Date Class with Mixin Trait Ord
class Date(y: Int, m: Int, d: Int)
extends Ord {
def year = y
def month = m
def day = d
override def toString(): String =
year + "-" + month + "-" + day
// … need definition of < and equals
}
Can only extend one class or trait
May mix-in additional classes using keyword with
Trang 28Date Class Equals Method
override def equals(that: Any): Boolean =
Trang 29Date Class < Method
def <(that: Any): Boolean = {
Trang 30object DateTest {
def main(args: Array[String]) {
val x = new Date(1,1,2000)
val y = new Date(12,31,2001)
Trang 32 Are often passed in a closure – with
references to free variables they
maninpulate
Provide ability to build powerful
libraries of higher-order functions
Trang 34Partial Application
scala> def addc(x: Int)(y: Int) = x + y
addc: (Int)(Int)Int
scala> val z = addc(1) _
z: (Int) => Int = <function>
scala> z(3)
res2: Int = 4
Trang 36Using 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)
Trang 37Other Higher Order List Methods
Trang 39Scala class hierarchy
Trang 40Actors in Scala
Trang 41 Concurrency is hard!
Real World is parallel and distributed.
Erlang's notion of a process:
Concurrent processes should pass
messages to other processes rather than share memory.
Erlang's processes are part of the language.
Scala's actors are part of the library.
Trang 42 Actors act independent of other actors.
Actors have mailboxes.
Actors communicate by sending messages to other actors.
Actors will check their mailbox and react to their messages.
Trang 43Message in a Bottle
Any object can be sent to an Actor
case object myMessageObject
myActor ! myMessageObject
Trang 44Please Mr Postman
How urgent is it?
react: I need it now!
receiveWithin: I need it soon!
receive: I'll wait.
All three methods will perform pattern matching on the objects received.
Trang 45Overactingimport scala.actors._
object SillyActor extends Actor {
def act() { // Defines how our actor acts
Trang 46Vegetable Launcher
case object Tomato
case object Lettuce
object VegetableLauncher extends Actor {