SlideShare a Scribd company logo
Patterns vs Abstractions

Code

Motivating Examples

Applications

SCALAZ BY EXAMPLE

Figure:

Credit http://www.flickr.com/photos/slambo_42

Susan Potter @SusanPotter
ScalaPDX January 2014
https://github.com/mbbx6spp/funalgebra

1
PATTERNS VS ABSTRACTIONS
Patterns vs Abstractions

Code

Motivating Examples

Applications

OO PATTERNS VS FP ABSTRACTIONS

→

More (Subjective -> Objective)

→ More (Ambiguous -> Precise)
→ "Fluffy" Interfaces -> Generic Functions

3
Patterns vs Abstractions

Code

Motivating Examples

Applications

LAYING BRICKS

4
Patterns vs Abstractions

Code

Motivating Examples

Applications

WARNING

→

Abstract Algebra -> (Continuous, Infinite)

→ Real World -> usually (Discrete, Finite)

5
CODE
Patterns vs Abstractions

Code

Motivating Examples

Applications

EXAMPLE UNIX PIPE

1
2
3

find . -name "*. rb" 
| xargs egrep "#.*? TODO:" 
| wc -l
Character-based, through file descriptors

7
Patterns vs Abstractions

Code

Motivating Examples

Applications

EXAMPLE FUNCTION COMPOSITION

1

( length . mapToUpper . sanitize ) input
Value based, through functions

8
Patterns vs Abstractions

Code

Motivating Examples

Applications

VALUING VALUES IN REAL WORLD
1

2

final case class Somefink [A](a: A) extends
PossiblyMaybe [A]
final case object Nowt extends PossiblyMaybe [
Nothing ]

3
4
5
6

7
8
9
10

sealed trait PossiblyMaybe [+A]
object PossiblyMaybeOps {
def noneDefault [A]( pm: PossiblyMaybe [A])(a:
A): A = pm match {
case Somefink (x) => x
case _ => a
}
}
Note _ in second match, caters for nulls with Java interop
9
Patterns vs Abstractions

Code

Motivating Examples

Applications

START WITH "CLOSED" MODEL

1
2
3
4
5
6
7
8
9

final case object Production extends Env
final case object Staging extends Env
final case class QA(n: Int) extends Env
final case class Dev(u: String ) extends Env
final case object Integration extends Env
sealed trait Env
object Env {
/* companion object code ... " instances " */
}

10
Patterns vs Abstractions

Code

Motivating Examples

Applications

EXTEND VIA ADHOC POLYMORPHISM
1
2
3
4
5
6

// companion object for Env
object Env {
// default " instances " over type Env
// for typeclasses below
implicit val EnvRead : Read[Env] = ???
implicit val EnvShow : Show[Env] = ???

7

// maybe you want ability to use
// one of two implementations of Order [Env]
// as well as Equal [Env ]. Anyone ?
implicit val EnvOrder : Order [Env] = ???
implicit val EnvEqual : Equal [Env] = ???

8
9
10
11
12
13

}

11
MOTIVATING EXAMPLES
Patterns vs Abstractions

Code

Motivating Examples

Applications

WHY USE IO MONAD?

→

Construct I/O "programs" from parts

→ Control error handling at runtime
→ Much easier to test various scenarios
→ And more …

13
Patterns vs Abstractions

Code

Motivating Examples

Applications

IO: "CONSTRUCTION" (1/2)
1

import scalaz ._, Scalaz ._, effect ._

2
3
4
5

trait MyApp {
def start (env: Env): IO[Unit]
}

6
7
8

def readConfig (env: Env):
IO[ BufferedSource ] = ???

9
10
11

def parseConfig (bs: BufferedSource ):
IO[Map[String , String ]] = ???

12
13
14

def setupMyApp (pool: ConnectionPool ):
IO[MyApp ] = ???
14
Patterns vs Abstractions

Code

Motivating Examples

Applications

IO: "CONSTRUCTION" (2/2)
1
2
3
4
5

def initialize (env: Env): IO[ MyApp] = for {
bs
<- readConfig (env)
map
<- parseConfig (bs)
app
<- setupMyApp (pool)
} yield app

6
7
8

def withCookieSessions (app: MyApp ):
IO[MyApp] = ???

9
10
11

def withServerSessions (app: MyApp ):
IO[MyApp] = ???

12
13
14
15
16

def run(env: Env): IO[Unit] = for {
app
<- initialize (env)
app2 <- withCookieSessions (app)
} yield app2. start (env)
15
Patterns vs Abstractions

Code

Motivating Examples

Applications

IO: ERROR HANDLING (1/2)
1

import scalaz ._, Scalaz ._, effect ._

2
3
4

def process (rq: Request ):
IO[ Response ] = ???

5
6
7

def showErrorTrace :
Throwable => IO[ Response ] = ???

8
9
10

def logErrorTrace :
Throwable => IO[ Response ] = ???

11
12
13

def reportErrorTrace :
Throwable => IO[ Response ] = ???

16
Patterns vs Abstractions

Code

Motivating Examples

Applications

IO: ERROR HANDLING (2/2)

1
2
3
4

def handleReq (rq: Request )( implicit e: Env) =
env match {
case Production =>
process (rq). except ( logErrorTrace )

5

case Staging =>
process (rq). except ( reportErrorTrace )

6
7
8

case _ =>
process (rq). except ( showErrorTrace )

9
10
11

}

17
Patterns vs Abstractions

Code

Motivating Examples

Applications

IO: TESTING EXAMPLE
1
2
3

import scala .io .{ BufferedSource , Codec }
import scalaz ._, Scalaz ._, effect ._
import java.io.{ ByteArrayInputStream => JBAIS
}

4
5
6
7
8
9
10
11
12

implicit val codec = Codec ("UTF -8")
IO(new BufferedSource (new JBAIS ("""{
"host": " localhost ",
"port": "5432",
" driver ": "my. awesome . PostgresDriver ",
" protocol ": " postgres ",
"name": " contactsdb "
}""". getBytes (codec . charSet ))))

18
Patterns vs Abstractions

Code

Motivating Examples

Applications

IO: TESTING EXAMPLE

1
2

// At the end of the universe we then do ...
run(env). unsafePerformIO

3
4
5

// or whatever your starting point is , e.g.
main(args). unsafePerformIO

6
7

// only ONCE ... most of the time ;)

19
Patterns vs Abstractions

Code

Motivating Examples

Applications

SAME TYPE, MANY "INTERFACES"

A type defined as a Monad (think: (>>=)) can also be used
as:
→

A Functor (think: fmap)

→ An Applicative (think: <*>, pure)
→ And possibly others

though not necessarily

20
APPLICATIONS
Patterns vs Abstractions

Code

Motivating Examples

Applications

KNOWN USES

→

Monoids:

Accumulators are everywhere, almost

→

Functors:

Lots of uses with common and user defined types

→

Monads:

→

Applicatives:

→

More:

Effects, "linear happy path", and more
"validations", safer Java interop, and more

e.g. Arrows, Zippers, Lenses, Tagged Types, …

22
Patterns vs Abstractions

Code

Motivating Examples

Applications

THINKING ALGEBRAICALLY

→

Properties:

→

Data Types:

→

Abstractions:

property based testing: quickcheck, scalacheck

start closed, extend using "type classes",
dependent types, etc when relevant
build small building blocks, use motar to

build solid walls
→

Dist Systems:

using algebraic abstractions, properties to
build more useful distributed systems

23
Patterns vs Abstractions

Code

Motivating Examples

Applications

QUESTIONS?

24

More Related Content

What's hot

Swift internals
Swift internalsSwift internals
Swift internals
Jung Kim
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
Wanbok Choi
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
David de Boer
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh Nair
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
Ingvar Stepanyan
 
Pragmatic sbt
Pragmatic sbtPragmatic sbt
Pragmatic sbt
Hermann Hueck
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Letswift Swift 3.0
Letswift Swift 3.0Letswift Swift 3.0
Letswift Swift 3.0
Sehyun Park
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
Ingvar Stepanyan
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
Domenic Denicola
 
Klee and angr
Klee and angrKlee and angr
Klee and angr
Wei-Bo Chen
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
Oswald Campesato
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
Jung Kim
 

What's hot (20)

Swift internals
Swift internalsSwift internals
Swift internals
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Pragmatic sbt
Pragmatic sbtPragmatic sbt
Pragmatic sbt
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Letswift Swift 3.0
Letswift Swift 3.0Letswift Swift 3.0
Letswift Swift 3.0
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Klee and angr
Klee and angrKlee and angr
Klee and angr
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Letswift19-clean-architecture
Letswift19-clean-architectureLetswift19-clean-architecture
Letswift19-clean-architecture
 

Viewers also liked

Scalaz
ScalazScalaz
Scalaz
mpilquist
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
Yeshwanth Kumar
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
oxbow_lakes
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
Scott Wlaschin
 
Age is not an int
Age is not an intAge is not an int
Age is not an int
oxbow_lakes
 
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)
Eugene Yokota
 
Link Walking with Riak
Link Walking with RiakLink Walking with Riak
Link Walking with Riak
Susan Potter
 
Writing Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScriptWriting Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScript
Susan Potter
 
Dynamo: Not Just For Datastores
Dynamo: Not Just For DatastoresDynamo: Not Just For Datastores
Dynamo: Not Just For Datastores
Susan Potter
 
From Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOS
Susan Potter
 
Distributed Developer Workflows using Git
Distributed Developer Workflows using GitDistributed Developer Workflows using Git
Distributed Developer Workflows using Git
Susan Potter
 
Ricon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak PipeRicon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak Pipe
Susan Potter
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
Susan Potter
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
Julien Truffaut
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
Susan Potter
 
Designing for Concurrency
Designing for ConcurrencyDesigning for Concurrency
Designing for Concurrency
Susan Potter
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
Paul Phillips
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
Susan Potter
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
kenbot
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
Knoldus Inc.
 

Viewers also liked (20)

Scalaz
ScalazScalaz
Scalaz
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Age is not an int
Age is not an intAge is not an int
Age is not an int
 
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)
The state of sbt 0.13, sbt server, and sbt 1.0 (ScalaSphere ver)
 
Link Walking with Riak
Link Walking with RiakLink Walking with Riak
Link Walking with Riak
 
Writing Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScriptWriting Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScript
 
Dynamo: Not Just For Datastores
Dynamo: Not Just For DatastoresDynamo: Not Just For Datastores
Dynamo: Not Just For Datastores
 
From Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOS
 
Distributed Developer Workflows using Git
Distributed Developer Workflows using GitDistributed Developer Workflows using Git
Distributed Developer Workflows using Git
 
Ricon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak PipeRicon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak Pipe
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
Designing for Concurrency
Designing for ConcurrencyDesigning for Concurrency
Designing for Concurrency
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Introduction to ScalaZ
Introduction to ScalaZIntroduction to ScalaZ
Introduction to ScalaZ
 

Similar to Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014

Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
Daniel Spector
 
Programming in Spark - Lessons Learned in OpenAire project
Programming in Spark - Lessons Learned in OpenAire projectProgramming in Spark - Lessons Learned in OpenAire project
Programming in Spark - Lessons Learned in OpenAire project
Łukasz Dumiszewski
 
It's always your fault
It's always your faultIt's always your fault
It's always your fault
Przemek Jakubczyk
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
Sadayuki Furuhashi
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
Nick Sieger
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
Andrey Karpov
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Mist - Serverless proxy to Apache Spark
Mist - Serverless proxy to Apache SparkMist - Serverless proxy to Apache Spark
Mist - Serverless proxy to Apache Spark
Вадим Челышов
 
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Provectus
 
Who pulls the strings?
Who pulls the strings?Who pulls the strings?
Who pulls the strings?
Ronny
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
Abbas Raza
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
PVS-Studio
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
PVS-Studio
 
Groovy on Grails by Ziya Askerov
Groovy on Grails by Ziya AskerovGroovy on Grails by Ziya Askerov
Groovy on Grails by Ziya Askerov
Vuqar Suleymanov
 
Grails
GrailsGrails
Grails
ziyaaskerov
 
Grails
GrailsGrails
Grails
ziyaaskerov
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
Andrey Karpov
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Enginecatherinewall
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
Fwdays
 

Similar to Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014 (20)

Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Programming in Spark - Lessons Learned in OpenAire project
Programming in Spark - Lessons Learned in OpenAire projectProgramming in Spark - Lessons Learned in OpenAire project
Programming in Spark - Lessons Learned in OpenAire project
 
It's always your fault
It's always your faultIt's always your fault
It's always your fault
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Mist - Serverless proxy to Apache Spark
Mist - Serverless proxy to Apache SparkMist - Serverless proxy to Apache Spark
Mist - Serverless proxy to Apache Spark
 
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
 
Who pulls the strings?
Who pulls the strings?Who pulls the strings?
Who pulls the strings?
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
 
Groovy on Grails by Ziya Askerov
Groovy on Grails by Ziya AskerovGroovy on Grails by Ziya Askerov
Groovy on Grails by Ziya Askerov
 
Grails
GrailsGrails
Grails
 
Grails
GrailsGrails
Grails
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Play framework
Play frameworkPlay framework
Play framework
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
 

More from Susan Potter

Thinking in Properties
Thinking in PropertiesThinking in Properties
Thinking in Properties
Susan Potter
 
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Susan Potter
 
From Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons LearnedFrom Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons Learned
Susan Potter
 
Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Susan Potter
 
Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)
Susan Potter
 
Deploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweatDeploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweat
Susan Potter
 

More from Susan Potter (7)

Thinking in Properties
Thinking in PropertiesThinking in Properties
Thinking in Properties
 
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
 
From Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons LearnedFrom Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons Learned
 
Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...
 
Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)
 
Twitter4R OAuth
Twitter4R OAuthTwitter4R OAuth
Twitter4R OAuth
 
Deploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweatDeploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweat
 

Recently uploaded

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 

Recently uploaded (20)

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 

Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014

  • 1. Patterns vs Abstractions Code Motivating Examples Applications SCALAZ BY EXAMPLE Figure: Credit http://www.flickr.com/photos/slambo_42 Susan Potter @SusanPotter ScalaPDX January 2014 https://github.com/mbbx6spp/funalgebra 1
  • 3. Patterns vs Abstractions Code Motivating Examples Applications OO PATTERNS VS FP ABSTRACTIONS → More (Subjective -> Objective) → More (Ambiguous -> Precise) → "Fluffy" Interfaces -> Generic Functions 3
  • 4. Patterns vs Abstractions Code Motivating Examples Applications LAYING BRICKS 4
  • 5. Patterns vs Abstractions Code Motivating Examples Applications WARNING → Abstract Algebra -> (Continuous, Infinite) → Real World -> usually (Discrete, Finite) 5
  • 7. Patterns vs Abstractions Code Motivating Examples Applications EXAMPLE UNIX PIPE 1 2 3 find . -name "*. rb" | xargs egrep "#.*? TODO:" | wc -l Character-based, through file descriptors 7
  • 8. Patterns vs Abstractions Code Motivating Examples Applications EXAMPLE FUNCTION COMPOSITION 1 ( length . mapToUpper . sanitize ) input Value based, through functions 8
  • 9. Patterns vs Abstractions Code Motivating Examples Applications VALUING VALUES IN REAL WORLD 1 2 final case class Somefink [A](a: A) extends PossiblyMaybe [A] final case object Nowt extends PossiblyMaybe [ Nothing ] 3 4 5 6 7 8 9 10 sealed trait PossiblyMaybe [+A] object PossiblyMaybeOps { def noneDefault [A]( pm: PossiblyMaybe [A])(a: A): A = pm match { case Somefink (x) => x case _ => a } } Note _ in second match, caters for nulls with Java interop 9
  • 10. Patterns vs Abstractions Code Motivating Examples Applications START WITH "CLOSED" MODEL 1 2 3 4 5 6 7 8 9 final case object Production extends Env final case object Staging extends Env final case class QA(n: Int) extends Env final case class Dev(u: String ) extends Env final case object Integration extends Env sealed trait Env object Env { /* companion object code ... " instances " */ } 10
  • 11. Patterns vs Abstractions Code Motivating Examples Applications EXTEND VIA ADHOC POLYMORPHISM 1 2 3 4 5 6 // companion object for Env object Env { // default " instances " over type Env // for typeclasses below implicit val EnvRead : Read[Env] = ??? implicit val EnvShow : Show[Env] = ??? 7 // maybe you want ability to use // one of two implementations of Order [Env] // as well as Equal [Env ]. Anyone ? implicit val EnvOrder : Order [Env] = ??? implicit val EnvEqual : Equal [Env] = ??? 8 9 10 11 12 13 } 11
  • 13. Patterns vs Abstractions Code Motivating Examples Applications WHY USE IO MONAD? → Construct I/O "programs" from parts → Control error handling at runtime → Much easier to test various scenarios → And more … 13
  • 14. Patterns vs Abstractions Code Motivating Examples Applications IO: "CONSTRUCTION" (1/2) 1 import scalaz ._, Scalaz ._, effect ._ 2 3 4 5 trait MyApp { def start (env: Env): IO[Unit] } 6 7 8 def readConfig (env: Env): IO[ BufferedSource ] = ??? 9 10 11 def parseConfig (bs: BufferedSource ): IO[Map[String , String ]] = ??? 12 13 14 def setupMyApp (pool: ConnectionPool ): IO[MyApp ] = ??? 14
  • 15. Patterns vs Abstractions Code Motivating Examples Applications IO: "CONSTRUCTION" (2/2) 1 2 3 4 5 def initialize (env: Env): IO[ MyApp] = for { bs <- readConfig (env) map <- parseConfig (bs) app <- setupMyApp (pool) } yield app 6 7 8 def withCookieSessions (app: MyApp ): IO[MyApp] = ??? 9 10 11 def withServerSessions (app: MyApp ): IO[MyApp] = ??? 12 13 14 15 16 def run(env: Env): IO[Unit] = for { app <- initialize (env) app2 <- withCookieSessions (app) } yield app2. start (env) 15
  • 16. Patterns vs Abstractions Code Motivating Examples Applications IO: ERROR HANDLING (1/2) 1 import scalaz ._, Scalaz ._, effect ._ 2 3 4 def process (rq: Request ): IO[ Response ] = ??? 5 6 7 def showErrorTrace : Throwable => IO[ Response ] = ??? 8 9 10 def logErrorTrace : Throwable => IO[ Response ] = ??? 11 12 13 def reportErrorTrace : Throwable => IO[ Response ] = ??? 16
  • 17. Patterns vs Abstractions Code Motivating Examples Applications IO: ERROR HANDLING (2/2) 1 2 3 4 def handleReq (rq: Request )( implicit e: Env) = env match { case Production => process (rq). except ( logErrorTrace ) 5 case Staging => process (rq). except ( reportErrorTrace ) 6 7 8 case _ => process (rq). except ( showErrorTrace ) 9 10 11 } 17
  • 18. Patterns vs Abstractions Code Motivating Examples Applications IO: TESTING EXAMPLE 1 2 3 import scala .io .{ BufferedSource , Codec } import scalaz ._, Scalaz ._, effect ._ import java.io.{ ByteArrayInputStream => JBAIS } 4 5 6 7 8 9 10 11 12 implicit val codec = Codec ("UTF -8") IO(new BufferedSource (new JBAIS ("""{ "host": " localhost ", "port": "5432", " driver ": "my. awesome . PostgresDriver ", " protocol ": " postgres ", "name": " contactsdb " }""". getBytes (codec . charSet )))) 18
  • 19. Patterns vs Abstractions Code Motivating Examples Applications IO: TESTING EXAMPLE 1 2 // At the end of the universe we then do ... run(env). unsafePerformIO 3 4 5 // or whatever your starting point is , e.g. main(args). unsafePerformIO 6 7 // only ONCE ... most of the time ;) 19
  • 20. Patterns vs Abstractions Code Motivating Examples Applications SAME TYPE, MANY "INTERFACES" A type defined as a Monad (think: (>>=)) can also be used as: → A Functor (think: fmap) → An Applicative (think: <*>, pure) → And possibly others though not necessarily 20
  • 22. Patterns vs Abstractions Code Motivating Examples Applications KNOWN USES → Monoids: Accumulators are everywhere, almost → Functors: Lots of uses with common and user defined types → Monads: → Applicatives: → More: Effects, "linear happy path", and more "validations", safer Java interop, and more e.g. Arrows, Zippers, Lenses, Tagged Types, … 22
  • 23. Patterns vs Abstractions Code Motivating Examples Applications THINKING ALGEBRAICALLY → Properties: → Data Types: → Abstractions: property based testing: quickcheck, scalacheck start closed, extend using "type classes", dependent types, etc when relevant build small building blocks, use motar to build solid walls → Dist Systems: using algebraic abstractions, properties to build more useful distributed systems 23
  • 24. Patterns vs Abstractions Code Motivating Examples Applications QUESTIONS? 24