SlideShare a Scribd company logo
Programming in Scala
Lecture Four
Angelo Corsaro
15 December 2017
Chief Technology Officer, ADLINK Technology Inc.
Table of contents
1. Implicits
2. Monads: A Gentle Introduction
3. Parallel and Concurrent Computations
1
Implicits
Scala Implicits
Scala implicit definitions provide a general mechanism to control how the
compiler resolves types or argument mismatches.
In other terms, it control the set of transformation available to the compiler to
fix a compile time error.
2
Example
Suppose we have a function that sums the elements of a lists and we want to
also use it to sum arrays.
If we just pass an array the compiler will raise a type error as he does not know
how to convert an Array[Int] into a List[Int].
def sum(xs: List[Int]): Int = xs match {
case List() => 0
case y::ys => y + sum(ys)
}
sum(Array[Int](1,3,4,5,6)) // Compiler error!
3
Implicit Functions
To fix this error and allow this function operate on Arrays as well as on List we
can define an implicit conversion as shown below:
import scala.language.implicitConversions
object Converter {
implicit def array2List(as: Array[Int])= as.toList
implicit def strintToInt(s: String) = s.toInt
}
import Converter._
sum(Array(1,3,4,5,6)) // Compiler inserts the conversion array2List
sum(Array[Int](1,"3",4,"5",6)) // Compiler inserts the conversions array2List and stringToInt
4
Implicit Classes
Implicit classes are commonly used to emulate open classes in Scala.
In other terms, one can define implicit transformation to extend or enrich the
protocol supported bu given type.
Example
object Implicits {
implicit class RichRunnable[T](runner: => T) extends Runnable {
def run() { runner() }
}
}
val thread = new Thread {
print("Hello!")
}
5
Implicit Parameters
Implicit parameters can be used to let the compiler fill in missing parameters in
curried functions.
Example
object Logger {
def log(msg: String)(implicit prompt: String) {
println(prompt + msg)
}
}
implicit val defaultPrompt = ">>> "
Logger.log("Testing logger")
6
Implicit Resolution Rules
The compiler looks for potential conversions available in the current scope.
Thus, conversions needs to be imported in order for the compiler to apply them.
7
Monads: A Gentle Introduction
Monad: Basic Idea
Monads can be thought of as composable computation descriptions.
The essence of monad is the separation of composition timeline from the
composed computation’s execution timeline, as well as the ability of computation
to implicitly carry extra data, as pertaining to the computation itself, in addition
to its one (hence the name) output, that it will produce when run (or queried, or
called upon).
This lends monads to supplementing pure calculations with features like I/O,
common environment, updatable state, etc.
8
Monad: Basic Idea / Cont.
Each monad, or computation type, provides means, subject to Monad Laws, to:
• create a description of a computation that will produce (a.k.a. ”return”) a
value, and
• combine (a.k.a. ”bind”) a computation description with a reaction to it, a
pure function that is set to receive a computation-produced value (when and
if that happens) and return another computation description.
Reactions are thus computation description constructors. A monad might also
define additional primitives to provide access to and/or enable manipulation of
data it implicitly carries, specific to its nature; cause some specific side-effects;
etc..
9
Monad Class and Monad Laws
Monads can be viewed as a standard programming interface to various data or
control structures, which is captured by the Monad class. All common monads
are members of it:
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
fail :: String -> m a
In addition to implementing the class functions, all instances of Monad should
obey the following equations, or Monad Laws:
return a >>= k = k a
m >>= return = m
m >>= (x -> k x >>= h) = (m >>= k) >>= h
10
Maybe Monad
The Haskell Maybe type is defined as:
data Maybe a = Just a | Nothing
deriving (Eq, Ord)
It is an instance of the Monad and Functor classes.
11
Maybe Monad Implementation
Let’s see how the Monad operations are defined for the Maybe type:
return :: a -> Maybe a
return x = Just x
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
(>>=) Nothing _ = Nothing
(>>=) (Just x) f = f x
(>>) :: Maybe a -> Maybe b -> Maybe b
(>>) x y = x >>= (_ -> y)
12
Verifying the First Monad Laws for Maybe
The first law states that:
return a >>= k = k a
Let’s play the substitution game:
return a >>= Just a >>= k = k a
13
Verifying the Second Monad Laws for Maybe
The second law states that:
m >>= return = m
Let’s play the substitution game:
Just x >>= return = return x = Just x
Nothing >>= return = Nothing
14
Verifying the Third Monad Laws for Maybe
The third law states that:
m >>= (x -> k x >>= h) = (m >>= k) >>= h
Let’s play the substitution game:
Just x >>= (y -> k y >>= h) = Just k x >>= h = (Just k x) >>= h = (Just x >>= k) >>= h
Thus we have proved that the Maybe type satisfies the three key monads rule.
There are types you are already familiar with that satisfy the monadic laws, such
as lists.
15
Monads in Scala
Scala does not define a Monad higher-order type, but monadic type (as well as
some time that are not strictly monads), provide the key monadic operations.
These operations, however are named differently.
16
Option Type in Scala
The Option type is Scala’s equivalent to Haskell’s Maybe Monad. Looking at it
is a good way of learning about monadic computations in Scala.
The Option type is defined as follows:
sealed abstract class Option[+A] extends Product with Serializable
case object None extends Option[Nothing] {
// ...
}
final case class Some[+A](value: A) extends Option[A] {
// ...
}
17
Option Type in Scala
The monad operations provided are the following:
// this is the equivalent of Haskell's bind (>>=)
def flatMap[B](f: A => Option[B]): Option[B]
Notice that the equivalent of return is the constructor. That said, Scala does not
provide the sequencing operator (>>). But as we’ve seen that can be easily
defined from bind.
The Option type is technically also a functor (as lists also are), thus it also
provides the map operation.
// this is the equivalent of Haskell's bind (>>=)
def map[B](f: A => B): B
18
Monadic Computation with the Option Type
def parseInt(s: String): Option[Int] = {
try {
Some(s.toInt)
} catch {
case e: java.lang.NumberFormatException => None
}
}
val x = parseInt("10")
val y = parseInt("10")
val z = x.flatMap(a => y.flatMap(b => Some(a+b)))
// Or using for
for (a <- x; b <- y) yield (a + b)
19
Parallel and Concurrent
Computations
Motivation
As the number of cores on processors are constantly increasing while the clock
frequencies are essentially stagnating, exploiting the additional computational
power requires to leverage parallel and concurrent computations.
Scala provides some elegant mechanism for supporting both parallel as well as
concurrent computations.
20
Parallel Collections
Scala supports the following parallel collections:
• ParArray
• ParVector
• mutable.ParHashMap
• mutable.ParHashSet
• immutable.ParHashMap
• immutable.ParHashSet
• ParRange
• ParTrieMap
21
Using Parallel Collections
Using parallel collections is rather trivial. A parallel collection can be created
from a regular one by using the .par property.
Example
val parArray = (1 to 10000).toArray.par
parArray.fold(0)(_ + _)
val lastNames = List("Smith","Jones","Frankenstein","Bach","Jackson","Rodin").par
lastNames.map(_.toUpperCase)
Given this out-of-order semantics, also must be careful to perform only
associative operations in order to avoid non-determinism.
22
Concurrent Computation on the JVM
The traditional approach to concurrent computations on the JVM is to leverage
threads and the built-in support for monitors, through the synchronized keyword,
to avoid race conditions.
This concurrency model is based on the assumption that different threads of
execution collaborate by mutating some shared state. This shared state has to be
protected to avoid race conditions.
This programming model is quite error-prone and is often source of bugs that are
very hard to debug due to the inherent non-determinism of concurrent
computations.
Furthermore, lock-based synchronization can lead to deadlocks.
23
Scala futures
Scala provide a mechanism for concurrent execution that makes it easier to work
under the share nothing model and that support more importantly supports
composability.
This mechanism is provided by Scala’s futures.
Futures are monads, thus, you can operate and compose them as any other
monad.
24
Futures Example
Below is an example of computing and composing futures.
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
val f1 = Future {
Thread.sleep(2)
10
}
val f2 = Future {
Thread.sleep(1)
20
}
val c = for (a <- f1; b <- f2) yield a + b
c.onComplete(r => r.foreach(a => println(a)))
25
Promises
The most general way of creating a future and is through promises.
The completion of future create from a promise is controlled by completing the
promise.
Example
def asynchComputation(): Future[Int]
import Converters._
val promise = Promise[Int]
new Thread {
val r = someComputeIntenseFun()
promise.success(r)
}.start()
return promise.future
}
26
Homeworks
Reading Assignment
Read the following chapters:
• Chapter 21
• Chapter 32
27

More Related Content

PDF
Programming in Scala - Lecture Three
Angelo Corsaro
 
PDF
Programming in Scala - Lecture Two
Angelo Corsaro
 
PDF
Programming in Scala - Lecture One
Angelo Corsaro
 
PDF
Functional Programming in Scala: Notes
Roberto Casadei
 
PDF
Google06
Zhiwen Guo
 
PPT
Scala
Zhiwen Guo
 
PDF
Applicative Functor - Part 3
Philip Schwarz
 
PPT
Functional object
ruchijindal87
 
Programming in Scala - Lecture Three
Angelo Corsaro
 
Programming in Scala - Lecture Two
Angelo Corsaro
 
Programming in Scala - Lecture One
Angelo Corsaro
 
Functional Programming in Scala: Notes
Roberto Casadei
 
Google06
Zhiwen Guo
 
Scala
Zhiwen Guo
 
Applicative Functor - Part 3
Philip Schwarz
 
Functional object
ruchijindal87
 

What's hot (20)

PDF
Getting Started With Scala
Xebia IT Architects
 
ODP
Pattern Matching - at a glance
Knoldus Inc.
 
PDF
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
Philip Schwarz
 
PDF
Programming in Scala: Notes
Roberto Casadei
 
ODP
Knolx session
Knoldus Inc.
 
PPTX
Tokens expressionsin C++
HalaiHansaika
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
PDF
Demystifying functional programming with Scala
Denis
 
PPTX
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
PDF
Introduction to programming in scala
Amuhinda Hungai
 
PDF
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Wim Vanderbauwhede
 
PDF
Object Oriented Programming using C++ Part III
Ajit Nayak
 
PDF
Functional programming in Scala
Damian Jureczko
 
RTF
Imp_Points_Scala
Nagavarunkumar Kolla
 
PDF
Haskell
Roberto Casadei
 
PDF
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Philip Schwarz
 
PDF
Lecture 5: Functional Programming
Eelco Visser
 
PDF
Arrays-Computer programming
nmahi96
 
PDF
Templates
Pranali Chaudhari
 
PPTX
C# String
Raghuveer Guthikonda
 
Getting Started With Scala
Xebia IT Architects
 
Pattern Matching - at a glance
Knoldus Inc.
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
Philip Schwarz
 
Programming in Scala: Notes
Roberto Casadei
 
Knolx session
Knoldus Inc.
 
Tokens expressionsin C++
HalaiHansaika
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Demystifying functional programming with Scala
Denis
 
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Introduction to programming in scala
Amuhinda Hungai
 
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Wim Vanderbauwhede
 
Object Oriented Programming using C++ Part III
Ajit Nayak
 
Functional programming in Scala
Damian Jureczko
 
Imp_Points_Scala
Nagavarunkumar Kolla
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Philip Schwarz
 
Lecture 5: Functional Programming
Eelco Visser
 
Arrays-Computer programming
nmahi96
 
Ad

Similar to Programming in Scala - Lecture Four (20)

PDF
Implicit conversion and parameters
Knoldus Inc.
 
ODP
Functional programming with Scala
Neelkanth Sachdeva
 
PPTX
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
PDF
Oct.22nd.Presentation.Final
Andrey Skripnikov
 
ODP
Functional Programming With Scala
Knoldus Inc.
 
PDF
Lecture 3
Muhammad Fayyaz
 
PDF
scala.reflect, Eugene Burmako
Vasil Remeniuk
 
PDF
Евгений Бурмако «scala.reflect»
e-Legion
 
PDF
Practical cats
Raymond Tay
 
PDF
Functional Programming in JavaScript
Will Livengood
 
PDF
List-based Monadic Computations for Dynamic Languages
Wim Vanderbauwhede
 
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
PDF
Dsp lab _eec-652__vi_sem_18012013
amanabr
 
PDF
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
PPT
MatlabIntro1234.ppt.....................
RajeshMadarkar
 
PPT
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
IrlanMalik
 
PPT
MatlabIntro.ppt
ShwetaPandey248972
 
PPT
MatlabIntro.ppt
konkatisandeepkumar
 
PPT
MatlabIntro.ppt
ssuser772830
 
Implicit conversion and parameters
Knoldus Inc.
 
Functional programming with Scala
Neelkanth Sachdeva
 
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
Oct.22nd.Presentation.Final
Andrey Skripnikov
 
Functional Programming With Scala
Knoldus Inc.
 
Lecture 3
Muhammad Fayyaz
 
scala.reflect, Eugene Burmako
Vasil Remeniuk
 
Евгений Бурмако «scala.reflect»
e-Legion
 
Practical cats
Raymond Tay
 
Functional Programming in JavaScript
Will Livengood
 
List-based Monadic Computations for Dynamic Languages
Wim Vanderbauwhede
 
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Dsp lab _eec-652__vi_sem_18012013
amanabr
 
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
MatlabIntro1234.ppt.....................
RajeshMadarkar
 
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
IrlanMalik
 
MatlabIntro.ppt
ShwetaPandey248972
 
MatlabIntro.ppt
konkatisandeepkumar
 
MatlabIntro.ppt
ssuser772830
 
Ad

More from Angelo Corsaro (20)

PDF
Zenoh: The Genesis
Angelo Corsaro
 
PDF
zenoh: The Edge Data Fabric
Angelo Corsaro
 
PDF
Zenoh Tutorial
Angelo Corsaro
 
PDF
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
Angelo Corsaro
 
PDF
zenoh: zero overhead pub/sub store/query compute
Angelo Corsaro
 
PDF
zenoh -- the ZEro Network OverHead protocol
Angelo Corsaro
 
PDF
zenoh -- the ZEro Network OverHead protocol
Angelo Corsaro
 
PDF
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Angelo Corsaro
 
PDF
Eastern Sicily
Angelo Corsaro
 
PDF
fog05: The Fog Computing Infrastructure
Angelo Corsaro
 
PDF
Cyclone DDS: Sharing Data in the IoT Age
Angelo Corsaro
 
PDF
fog05: The Fog Computing Platform
Angelo Corsaro
 
PDF
Data Sharing in Extremely Resource Constrained Envionrments
Angelo Corsaro
 
PDF
The DDS Security Standard
Angelo Corsaro
 
PDF
The Data Distribution Service
Angelo Corsaro
 
PDF
RUSTing -- Partially Ordered Rust Programming Ruminations
Angelo Corsaro
 
PDF
Vortex II -- The Industrial IoT Connectivity Standard
Angelo Corsaro
 
PDF
Fog Computing Defined
Angelo Corsaro
 
PDF
DDS In Action Part II
Angelo Corsaro
 
PDF
DDS in Action -- Part I
Angelo Corsaro
 
Zenoh: The Genesis
Angelo Corsaro
 
zenoh: The Edge Data Fabric
Angelo Corsaro
 
Zenoh Tutorial
Angelo Corsaro
 
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
Angelo Corsaro
 
zenoh: zero overhead pub/sub store/query compute
Angelo Corsaro
 
zenoh -- the ZEro Network OverHead protocol
Angelo Corsaro
 
zenoh -- the ZEro Network OverHead protocol
Angelo Corsaro
 
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Angelo Corsaro
 
Eastern Sicily
Angelo Corsaro
 
fog05: The Fog Computing Infrastructure
Angelo Corsaro
 
Cyclone DDS: Sharing Data in the IoT Age
Angelo Corsaro
 
fog05: The Fog Computing Platform
Angelo Corsaro
 
Data Sharing in Extremely Resource Constrained Envionrments
Angelo Corsaro
 
The DDS Security Standard
Angelo Corsaro
 
The Data Distribution Service
Angelo Corsaro
 
RUSTing -- Partially Ordered Rust Programming Ruminations
Angelo Corsaro
 
Vortex II -- The Industrial IoT Connectivity Standard
Angelo Corsaro
 
Fog Computing Defined
Angelo Corsaro
 
DDS In Action Part II
Angelo Corsaro
 
DDS in Action -- Part I
Angelo Corsaro
 

Recently uploaded (20)

PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Architecture of the Future (09152021)
EdwardMeyman
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
This slide provides an overview Technology
mineshkharadi333
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 

Programming in Scala - Lecture Four

  • 1. Programming in Scala Lecture Four Angelo Corsaro 15 December 2017 Chief Technology Officer, ADLINK Technology Inc.
  • 2. Table of contents 1. Implicits 2. Monads: A Gentle Introduction 3. Parallel and Concurrent Computations 1
  • 4. Scala Implicits Scala implicit definitions provide a general mechanism to control how the compiler resolves types or argument mismatches. In other terms, it control the set of transformation available to the compiler to fix a compile time error. 2
  • 5. Example Suppose we have a function that sums the elements of a lists and we want to also use it to sum arrays. If we just pass an array the compiler will raise a type error as he does not know how to convert an Array[Int] into a List[Int]. def sum(xs: List[Int]): Int = xs match { case List() => 0 case y::ys => y + sum(ys) } sum(Array[Int](1,3,4,5,6)) // Compiler error! 3
  • 6. Implicit Functions To fix this error and allow this function operate on Arrays as well as on List we can define an implicit conversion as shown below: import scala.language.implicitConversions object Converter { implicit def array2List(as: Array[Int])= as.toList implicit def strintToInt(s: String) = s.toInt } import Converter._ sum(Array(1,3,4,5,6)) // Compiler inserts the conversion array2List sum(Array[Int](1,"3",4,"5",6)) // Compiler inserts the conversions array2List and stringToInt 4
  • 7. Implicit Classes Implicit classes are commonly used to emulate open classes in Scala. In other terms, one can define implicit transformation to extend or enrich the protocol supported bu given type. Example object Implicits { implicit class RichRunnable[T](runner: => T) extends Runnable { def run() { runner() } } } val thread = new Thread { print("Hello!") } 5
  • 8. Implicit Parameters Implicit parameters can be used to let the compiler fill in missing parameters in curried functions. Example object Logger { def log(msg: String)(implicit prompt: String) { println(prompt + msg) } } implicit val defaultPrompt = ">>> " Logger.log("Testing logger") 6
  • 9. Implicit Resolution Rules The compiler looks for potential conversions available in the current scope. Thus, conversions needs to be imported in order for the compiler to apply them. 7
  • 10. Monads: A Gentle Introduction
  • 11. Monad: Basic Idea Monads can be thought of as composable computation descriptions. The essence of monad is the separation of composition timeline from the composed computation’s execution timeline, as well as the ability of computation to implicitly carry extra data, as pertaining to the computation itself, in addition to its one (hence the name) output, that it will produce when run (or queried, or called upon). This lends monads to supplementing pure calculations with features like I/O, common environment, updatable state, etc. 8
  • 12. Monad: Basic Idea / Cont. Each monad, or computation type, provides means, subject to Monad Laws, to: • create a description of a computation that will produce (a.k.a. ”return”) a value, and • combine (a.k.a. ”bind”) a computation description with a reaction to it, a pure function that is set to receive a computation-produced value (when and if that happens) and return another computation description. Reactions are thus computation description constructors. A monad might also define additional primitives to provide access to and/or enable manipulation of data it implicitly carries, specific to its nature; cause some specific side-effects; etc.. 9
  • 13. Monad Class and Monad Laws Monads can be viewed as a standard programming interface to various data or control structures, which is captured by the Monad class. All common monads are members of it: class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> m a fail :: String -> m a In addition to implementing the class functions, all instances of Monad should obey the following equations, or Monad Laws: return a >>= k = k a m >>= return = m m >>= (x -> k x >>= h) = (m >>= k) >>= h 10
  • 14. Maybe Monad The Haskell Maybe type is defined as: data Maybe a = Just a | Nothing deriving (Eq, Ord) It is an instance of the Monad and Functor classes. 11
  • 15. Maybe Monad Implementation Let’s see how the Monad operations are defined for the Maybe type: return :: a -> Maybe a return x = Just x (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b (>>=) Nothing _ = Nothing (>>=) (Just x) f = f x (>>) :: Maybe a -> Maybe b -> Maybe b (>>) x y = x >>= (_ -> y) 12
  • 16. Verifying the First Monad Laws for Maybe The first law states that: return a >>= k = k a Let’s play the substitution game: return a >>= Just a >>= k = k a 13
  • 17. Verifying the Second Monad Laws for Maybe The second law states that: m >>= return = m Let’s play the substitution game: Just x >>= return = return x = Just x Nothing >>= return = Nothing 14
  • 18. Verifying the Third Monad Laws for Maybe The third law states that: m >>= (x -> k x >>= h) = (m >>= k) >>= h Let’s play the substitution game: Just x >>= (y -> k y >>= h) = Just k x >>= h = (Just k x) >>= h = (Just x >>= k) >>= h Thus we have proved that the Maybe type satisfies the three key monads rule. There are types you are already familiar with that satisfy the monadic laws, such as lists. 15
  • 19. Monads in Scala Scala does not define a Monad higher-order type, but monadic type (as well as some time that are not strictly monads), provide the key monadic operations. These operations, however are named differently. 16
  • 20. Option Type in Scala The Option type is Scala’s equivalent to Haskell’s Maybe Monad. Looking at it is a good way of learning about monadic computations in Scala. The Option type is defined as follows: sealed abstract class Option[+A] extends Product with Serializable case object None extends Option[Nothing] { // ... } final case class Some[+A](value: A) extends Option[A] { // ... } 17
  • 21. Option Type in Scala The monad operations provided are the following: // this is the equivalent of Haskell's bind (>>=) def flatMap[B](f: A => Option[B]): Option[B] Notice that the equivalent of return is the constructor. That said, Scala does not provide the sequencing operator (>>). But as we’ve seen that can be easily defined from bind. The Option type is technically also a functor (as lists also are), thus it also provides the map operation. // this is the equivalent of Haskell's bind (>>=) def map[B](f: A => B): B 18
  • 22. Monadic Computation with the Option Type def parseInt(s: String): Option[Int] = { try { Some(s.toInt) } catch { case e: java.lang.NumberFormatException => None } } val x = parseInt("10") val y = parseInt("10") val z = x.flatMap(a => y.flatMap(b => Some(a+b))) // Or using for for (a <- x; b <- y) yield (a + b) 19
  • 24. Motivation As the number of cores on processors are constantly increasing while the clock frequencies are essentially stagnating, exploiting the additional computational power requires to leverage parallel and concurrent computations. Scala provides some elegant mechanism for supporting both parallel as well as concurrent computations. 20
  • 25. Parallel Collections Scala supports the following parallel collections: • ParArray • ParVector • mutable.ParHashMap • mutable.ParHashSet • immutable.ParHashMap • immutable.ParHashSet • ParRange • ParTrieMap 21
  • 26. Using Parallel Collections Using parallel collections is rather trivial. A parallel collection can be created from a regular one by using the .par property. Example val parArray = (1 to 10000).toArray.par parArray.fold(0)(_ + _) val lastNames = List("Smith","Jones","Frankenstein","Bach","Jackson","Rodin").par lastNames.map(_.toUpperCase) Given this out-of-order semantics, also must be careful to perform only associative operations in order to avoid non-determinism. 22
  • 27. Concurrent Computation on the JVM The traditional approach to concurrent computations on the JVM is to leverage threads and the built-in support for monitors, through the synchronized keyword, to avoid race conditions. This concurrency model is based on the assumption that different threads of execution collaborate by mutating some shared state. This shared state has to be protected to avoid race conditions. This programming model is quite error-prone and is often source of bugs that are very hard to debug due to the inherent non-determinism of concurrent computations. Furthermore, lock-based synchronization can lead to deadlocks. 23
  • 28. Scala futures Scala provide a mechanism for concurrent execution that makes it easier to work under the share nothing model and that support more importantly supports composability. This mechanism is provided by Scala’s futures. Futures are monads, thus, you can operate and compose them as any other monad. 24
  • 29. Futures Example Below is an example of computing and composing futures. import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future val f1 = Future { Thread.sleep(2) 10 } val f2 = Future { Thread.sleep(1) 20 } val c = for (a <- f1; b <- f2) yield a + b c.onComplete(r => r.foreach(a => println(a))) 25
  • 30. Promises The most general way of creating a future and is through promises. The completion of future create from a promise is controlled by completing the promise. Example def asynchComputation(): Future[Int] import Converters._ val promise = Promise[Int] new Thread { val r = someComputeIntenseFun() promise.success(r) }.start() return promise.future } 26
  • 32. Reading Assignment Read the following chapters: • Chapter 21 • Chapter 32 27