SlideShare a Scribd company logo
1 of 35
Building Enigma with 
State Monad & Lens 
Timothy Perrett 
SF Scala, December 2014
Hello.
73 years today.
Steckerbrett. 
(Plugboard)
Walzen. 
(Rotor)
Umkehrwalze. 
(Reflector)
Process.
158,962,555,217,826,360,000. 
(158 quintillion)
Process. 
๏ Distributed with typically a month of 
configuration settings. 
๏ Kriegsmarine vessels often had two 
Enigmas onboard to account for delivery 
delay due to being submersed
Demo.
Design.
Design.
Design. 
Char => Char 
Char => Char 
Char => Char 
Char => Char
Code.
case class Plugboard(shuffled: Seq[Char]){ ... } 
case class Rotor( 
wiring: String, 
ring: Char, 
notch: Char, 
posistion: Char 
){ ... } 
case class Machine( 
plugboard: Plugboard, 
right: Rotor, 
middle: Rotor, 
left: Rotor, 
reflector: Reflector 
){ ... } 
Algebra.
for { 
Program. 
_ <- get[Machine] 
_ <- modify((m: Machine) => right(m)) 
_ <- modify((m: Machine) => middle(m)) 
_ <- modify((m: Machine) => left(m)) 
o <- get[Machine] 
} yield 
o.plugboard.transform _ andThen 
rtl(o) andThen 
o.reflector.transform andThen 
ltr(o) andThen o.plugboard.transform apply(c)
State. 
S => (S, A) 
๏ Given a state S, compute a resulting S 
(i.e. make any needed modifications to 
the state) and produce a resulting A 
๏ Explicit state handling in every type 
signature can be tedious.
trait State[S,A] { 
def get[S]: State[S,S] 
def put[S](s: S): State[S, Unit] 
def modify[S](f: S => S): State[S, Unit] 
def run(s: S): (S,A) 
def map[B](f: A => B): State[S,B] 
def flatMap[B](f: A => State[S, B]): State[S,B] 
} 
object State { 
def apply[S,A](f: S => (S,A)): State[S, A] = 
new State[S,A]{ 
def run(s: S): (S,A) = f(s) 
} 
} 
State.
trait State[S,A] { 
def run(s: S): (S,A) 
def map[B](f: A => B): State[S,B] = State { s => 
val (x,a) = run(s) 
(x,f(a)) 
} 
def flatMap[B](f: A => State[S, B]): State[S,B] = 
State { s => 
val (x,a) = run(s) 
f(a).run(s) 
} 
} 
State.
State. 
type State[S,A] 
๏ State monad threads S through your 
computation for you. 
๏ Actual implementation in Scalaz is in 
terms of the monad transformer for State 
through Id. 
๏ Avoid overflow by using: 
type State[S,A] = StateT[Trampoline,S,A]
for { 
Program. 
_ <- get[Machine] 
_ <- modify((m: Machine) => right(m)) 
_ <- modify((m: Machine) => middle(m)) 
_ <- modify((m: Machine) => left(m)) 
o <- get[Machine] 
} yield 
o.plugboard.transform _ andThen 
rtl(o) andThen 
o.reflector.transform andThen 
ltr(o) andThen o.plugboard.transform apply(c)
Program. 
def stepRotor(r: Rotor): Rotor = 
rotorL.modify(r, Alphabet.nextLetter) 
def right(m: Machine): Machine = 
m |-> rightL modify(stepRotor) 
def middle(m: Machine): Machine = 
m |-> middleL modify(r => 
if(m.right.notch == r.position || 
m.left.notch == r.position) stepRotor(r) 
else r) 
def left(m: Machine): Machine = 
m |-> leftL modify(r => 
if(r.position == m.middle.notch) stepRotor(r) 
else r)
Lens. 
get: A => B 
set: (A,B) => A 
๏ Comprised of two functions: “getter” and 
“setter”, where the latter returns the 
updated value. 
๏ Using lenses, updates compose
m.copy( 
right = m.right.copy( 
position = m.right.position + 1 
), 
middle = m.middle.copy( 
position = m.middle.position + 1 
), 
left = m.left.copy( 
position = m.left.position + 1 
) 
) 
Lens.
Lens. 
case class Lens[A,B]( 
get: A => B, 
set: (A, B) => A 
) 
val rotorL = Lens[Rotor, Char]( 
_.position, 
(a, b) => a.copy(position = b) 
) 
rotorL.set(m.right)
Lens. 
type Lens[A,B] 
๏ Build modular functions to compose 
updates to complex domain types. 
๏ Scalaz ships with a Lens 
implementation, but Monocle is really 
where its at for Lenses
Monocle. 
https://github.com/julien-truffaut/Monocle 
๏ Scalaz Lens is great, but has boilerplate 
๏ Monocle removes said boilerplate by 
using macros 
๏ Provides powerful abstractions in the 
same space as Lens (Prism, Iso, Getter) 
๏ Convenient syntax for bedazzlement 
of lenses
Monocle. 
val lenserM = Lenser[Machine] 
val rightL = lenserM(_.right) 
val middleL = lenserM(_.middle) 
val leftL = lenserM(_.left) 
val lenserR = Lenser[Rotor] 
val rotorL: Lens[Rotor,Rotor,Char,Char] = 
lenserR(_.position) 
m |-> rightL |-> rotorL modify(_ + 1)
Roundup. 
๏ FP gives you a frame to reason about 
problems in a straight-forward, explicit 
and easy manner. 
๏ State monad gives you explicit, 
immutable control over state changes 
๏ Lenses make updating nested domain 
types convenient and composable. 
๏ Enigma was an incredible piece of 
engineering in 1918!
EOF 
@timperrett 
github.com/timperrett/enigma 
timperrett.com

More Related Content

What's hot

Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門Takashi Imahiro
 
Ozma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyOzma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyBeScala
 
Introduction to lambda expression & lambda calculus
Introduction to lambda expression & lambda calculusIntroduction to lambda expression & lambda calculus
Introduction to lambda expression & lambda calculusKim Leo
 
Loom and Graphs in Clojure
Loom and Graphs in ClojureLoom and Graphs in Clojure
Loom and Graphs in ClojureAysylu Greenberg
 
Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015Aysylu Greenberg
 

What's hot (10)

Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門
 
2DCompsitionEngine
2DCompsitionEngine2DCompsitionEngine
2DCompsitionEngine
 
Ozma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyOzma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrency
 
Matlab
MatlabMatlab
Matlab
 
Introduction to lambda expression & lambda calculus
Introduction to lambda expression & lambda calculusIntroduction to lambda expression & lambda calculus
Introduction to lambda expression & lambda calculus
 
Loom at Clojure/West
Loom at Clojure/WestLoom at Clojure/West
Loom at Clojure/West
 
Loom and Graphs in Clojure
Loom and Graphs in ClojureLoom and Graphs in Clojure
Loom and Graphs in Clojure
 
Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015Loom & Functional Graphs in Clojure @ LambdaConf 2015
Loom & Functional Graphs in Clojure @ LambdaConf 2015
 
Differentiation and its applications
Differentiation and its applications Differentiation and its applications
Differentiation and its applications
 
1
11
1
 

Similar to Building Enigma with State Monad & Lens

Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeIlan Godik
 
Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2Hang Zhao
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bPhilip Schwarz
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...
Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...
Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...Databricks
 
CS 354 Graphics Math
CS 354 Graphics MathCS 354 Graphics Math
CS 354 Graphics MathMark Kilgard
 
Transducers in JavaScript
Transducers in JavaScriptTransducers in JavaScript
Transducers in JavaScriptPavel Forkert
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemJohn De Goes
 
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...Thejaka Amila Kanewala, Ph.D.
 
34. Cam is a mechanical device that transforms rotary motion into lin.pdf
34. Cam is a mechanical device that transforms rotary motion into lin.pdf34. Cam is a mechanical device that transforms rotary motion into lin.pdf
34. Cam is a mechanical device that transforms rotary motion into lin.pdfssuserc77a341
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Raffi Krikorian
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciencesalexstorer
 
Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017Jonathon Brouse
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scalaPiotr Paradziński
 
Rendering Art on the Web - A Performance compendium
Rendering Art on the Web - A Performance compendiumRendering Art on the Web - A Performance compendium
Rendering Art on the Web - A Performance compendiumRaimon Ràfols
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Monadologie
MonadologieMonadologie
Monadologieleague
 

Similar to Building Enigma with State Monad & Lens (20)

Optics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the wholeOptics with monocle - Modeling the part and the whole
Optics with monocle - Modeling the part and the whole
 
Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1b
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...
Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...
Building Machine Learning Algorithms on Apache Spark: Scaling Out and Up with...
 
CS 354 Graphics Math
CS 354 Graphics MathCS 354 Graphics Math
CS 354 Graphics Math
 
Transducers in JavaScript
Transducers in JavaScriptTransducers in JavaScript
Transducers in JavaScript
 
The Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect SystemThe Design of the Scalaz 8 Effect System
The Design of the Scalaz 8 Effect System
 
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
 
34. Cam is a mechanical device that transforms rotary motion into lin.pdf
34. Cam is a mechanical device that transforms rotary motion into lin.pdf34. Cam is a mechanical device that transforms rotary motion into lin.pdf
34. Cam is a mechanical device that transforms rotary motion into lin.pdf
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Data transformation-cheatsheet
Data transformation-cheatsheetData transformation-cheatsheet
Data transformation-cheatsheet
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
ComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical SciencesComputeFest 2012: Intro To R for Physical Sciences
ComputeFest 2012: Intro To R for Physical Sciences
 
Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
Rendering Art on the Web - A Performance compendium
Rendering Art on the Web - A Performance compendiumRendering Art on the Web - A Performance compendium
Rendering Art on the Web - A Performance compendium
 
Ray Tracing with ZIO
Ray Tracing with ZIORay Tracing with ZIO
Ray Tracing with ZIO
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Monadologie
MonadologieMonadologie
Monadologie
 

More from Timothy Perrett

Nelson: Rigorous Deployment for a Functional World
Nelson: Rigorous Deployment for a Functional WorldNelson: Rigorous Deployment for a Functional World
Nelson: Rigorous Deployment for a Functional WorldTimothy Perrett
 
Online Experimentation with Immutable Infrastructure
Online Experimentation with Immutable InfrastructureOnline Experimentation with Immutable Infrastructure
Online Experimentation with Immutable InfrastructureTimothy Perrett
 
Enterprise Algebras, Scala World 2016
Enterprise Algebras, Scala World 2016Enterprise Algebras, Scala World 2016
Enterprise Algebras, Scala World 2016Timothy Perrett
 
Large-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at VerizonLarge-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at VerizonTimothy Perrett
 
Reasonable RPC with Remotely
Reasonable RPC with RemotelyReasonable RPC with Remotely
Reasonable RPC with RemotelyTimothy Perrett
 
Functional Programming at Verizon
Functional Programming at VerizonFunctional Programming at Verizon
Functional Programming at VerizonTimothy Perrett
 
Scalalable Language for a Scalable Web
Scalalable Language for a Scalable WebScalalable Language for a Scalable Web
Scalalable Language for a Scalable WebTimothy Perrett
 
Javazone 2011: Goal Directed Web Applications
Javazone 2011: Goal Directed Web ApplicationsJavazone 2011: Goal Directed Web Applications
Javazone 2011: Goal Directed Web ApplicationsTimothy Perrett
 
Concurrency and Parallelism with Scala
Concurrency and Parallelism with ScalaConcurrency and Parallelism with Scala
Concurrency and Parallelism with ScalaTimothy Perrett
 
Scaladays 2011: Task Driven Scala Web Applications
Scaladays 2011: Task Driven Scala Web ApplicationsScaladays 2011: Task Driven Scala Web Applications
Scaladays 2011: Task Driven Scala Web ApplicationsTimothy Perrett
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicTimothy Perrett
 
Devoxx 2009: The Lift Framework
Devoxx 2009: The Lift FrameworkDevoxx 2009: The Lift Framework
Devoxx 2009: The Lift FrameworkTimothy Perrett
 

More from Timothy Perrett (15)

Nelson: Rigorous Deployment for a Functional World
Nelson: Rigorous Deployment for a Functional WorldNelson: Rigorous Deployment for a Functional World
Nelson: Rigorous Deployment for a Functional World
 
Online Experimentation with Immutable Infrastructure
Online Experimentation with Immutable InfrastructureOnline Experimentation with Immutable Infrastructure
Online Experimentation with Immutable Infrastructure
 
Enterprise Algebras, Scala World 2016
Enterprise Algebras, Scala World 2016Enterprise Algebras, Scala World 2016
Enterprise Algebras, Scala World 2016
 
Large-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at VerizonLarge-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at Verizon
 
Reasonable RPC with Remotely
Reasonable RPC with RemotelyReasonable RPC with Remotely
Reasonable RPC with Remotely
 
Functional Programming at Verizon
Functional Programming at VerizonFunctional Programming at Verizon
Functional Programming at Verizon
 
Scalalable Language for a Scalable Web
Scalalable Language for a Scalable WebScalalable Language for a Scalable Web
Scalalable Language for a Scalable Web
 
BRUG - Hello, Scala
BRUG - Hello, ScalaBRUG - Hello, Scala
BRUG - Hello, Scala
 
Scala Helix
Scala HelixScala Helix
Scala Helix
 
Javazone 2011: Goal Directed Web Applications
Javazone 2011: Goal Directed Web ApplicationsJavazone 2011: Goal Directed Web Applications
Javazone 2011: Goal Directed Web Applications
 
Concurrency and Parallelism with Scala
Concurrency and Parallelism with ScalaConcurrency and Parallelism with Scala
Concurrency and Parallelism with Scala
 
Scaladays 2011: Task Driven Scala Web Applications
Scaladays 2011: Task Driven Scala Web ApplicationsScaladays 2011: Task Driven Scala Web Applications
Scaladays 2011: Task Driven Scala Web Applications
 
Bathcamp 2010-riak
Bathcamp 2010-riakBathcamp 2010-riak
Bathcamp 2010-riak
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-public
 
Devoxx 2009: The Lift Framework
Devoxx 2009: The Lift FrameworkDevoxx 2009: The Lift Framework
Devoxx 2009: The Lift Framework
 

Recently uploaded

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 

Recently uploaded (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 

Building Enigma with State Monad & Lens

  • 1. Building Enigma with State Monad & Lens Timothy Perrett SF Scala, December 2014
  • 3.
  • 6.
  • 8.
  • 10.
  • 12.
  • 14. Process. ๏ Distributed with typically a month of configuration settings. ๏ Kriegsmarine vessels often had two Enigmas onboard to account for delivery delay due to being submersed
  • 15. Demo.
  • 18. Design. Char => Char Char => Char Char => Char Char => Char
  • 19. Code.
  • 20. case class Plugboard(shuffled: Seq[Char]){ ... } case class Rotor( wiring: String, ring: Char, notch: Char, posistion: Char ){ ... } case class Machine( plugboard: Plugboard, right: Rotor, middle: Rotor, left: Rotor, reflector: Reflector ){ ... } Algebra.
  • 21. for { Program. _ <- get[Machine] _ <- modify((m: Machine) => right(m)) _ <- modify((m: Machine) => middle(m)) _ <- modify((m: Machine) => left(m)) o <- get[Machine] } yield o.plugboard.transform _ andThen rtl(o) andThen o.reflector.transform andThen ltr(o) andThen o.plugboard.transform apply(c)
  • 22. State. S => (S, A) ๏ Given a state S, compute a resulting S (i.e. make any needed modifications to the state) and produce a resulting A ๏ Explicit state handling in every type signature can be tedious.
  • 23. trait State[S,A] { def get[S]: State[S,S] def put[S](s: S): State[S, Unit] def modify[S](f: S => S): State[S, Unit] def run(s: S): (S,A) def map[B](f: A => B): State[S,B] def flatMap[B](f: A => State[S, B]): State[S,B] } object State { def apply[S,A](f: S => (S,A)): State[S, A] = new State[S,A]{ def run(s: S): (S,A) = f(s) } } State.
  • 24. trait State[S,A] { def run(s: S): (S,A) def map[B](f: A => B): State[S,B] = State { s => val (x,a) = run(s) (x,f(a)) } def flatMap[B](f: A => State[S, B]): State[S,B] = State { s => val (x,a) = run(s) f(a).run(s) } } State.
  • 25. State. type State[S,A] ๏ State monad threads S through your computation for you. ๏ Actual implementation in Scalaz is in terms of the monad transformer for State through Id. ๏ Avoid overflow by using: type State[S,A] = StateT[Trampoline,S,A]
  • 26. for { Program. _ <- get[Machine] _ <- modify((m: Machine) => right(m)) _ <- modify((m: Machine) => middle(m)) _ <- modify((m: Machine) => left(m)) o <- get[Machine] } yield o.plugboard.transform _ andThen rtl(o) andThen o.reflector.transform andThen ltr(o) andThen o.plugboard.transform apply(c)
  • 27. Program. def stepRotor(r: Rotor): Rotor = rotorL.modify(r, Alphabet.nextLetter) def right(m: Machine): Machine = m |-> rightL modify(stepRotor) def middle(m: Machine): Machine = m |-> middleL modify(r => if(m.right.notch == r.position || m.left.notch == r.position) stepRotor(r) else r) def left(m: Machine): Machine = m |-> leftL modify(r => if(r.position == m.middle.notch) stepRotor(r) else r)
  • 28. Lens. get: A => B set: (A,B) => A ๏ Comprised of two functions: “getter” and “setter”, where the latter returns the updated value. ๏ Using lenses, updates compose
  • 29. m.copy( right = m.right.copy( position = m.right.position + 1 ), middle = m.middle.copy( position = m.middle.position + 1 ), left = m.left.copy( position = m.left.position + 1 ) ) Lens.
  • 30. Lens. case class Lens[A,B]( get: A => B, set: (A, B) => A ) val rotorL = Lens[Rotor, Char]( _.position, (a, b) => a.copy(position = b) ) rotorL.set(m.right)
  • 31. Lens. type Lens[A,B] ๏ Build modular functions to compose updates to complex domain types. ๏ Scalaz ships with a Lens implementation, but Monocle is really where its at for Lenses
  • 32. Monocle. https://github.com/julien-truffaut/Monocle ๏ Scalaz Lens is great, but has boilerplate ๏ Monocle removes said boilerplate by using macros ๏ Provides powerful abstractions in the same space as Lens (Prism, Iso, Getter) ๏ Convenient syntax for bedazzlement of lenses
  • 33. Monocle. val lenserM = Lenser[Machine] val rightL = lenserM(_.right) val middleL = lenserM(_.middle) val leftL = lenserM(_.left) val lenserR = Lenser[Rotor] val rotorL: Lens[Rotor,Rotor,Char,Char] = lenserR(_.position) m |-> rightL |-> rotorL modify(_ + 1)
  • 34. Roundup. ๏ FP gives you a frame to reason about problems in a straight-forward, explicit and easy manner. ๏ State monad gives you explicit, immutable control over state changes ๏ Lenses make updating nested domain types convenient and composable. ๏ Enigma was an incredible piece of engineering in 1918!

Editor's Notes

  1. + Learn something about the enigma machine + Gain high-level overview of state monad and lens, such that you might want to try them out.
  2. 73 years ago to Mavis Batey cracked the M4 engima
  3. type Trampoline[A] = Free[Function0, A]
  4. With that, thank you very much for listening. If anyone has any questions I’d be happy to answer them.