SlideShare a Scribd company logo
1 of 61
Refactoring using Functional
Design Patterns
Mårten Rånge/Atomize AB
A("capabilityIdentity", Scalar, Iwd(2))
A("txPortMaximumOutputPower", P(dBm0_1, dBm0_1) , ProdDataXml("/board/powerClassUsage"))
A("txPortMaximumPar" , P(dBm0_1, dBm0_1) , SysDataParam("capMaxPar"))
A("txOperationBandLowEdge" , F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Then(Select(0)))
A("txOperationBandHighEdge", F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Then(Select(1)))
A("capabilityPortArray", Unspecified, CapabilityPortArray)
String (obviously) Enum Enum What type is this?
A("txOperationBandLowEdge" , F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Then(Select(0)))
A("txOperationBandHighEdge", F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Then(Select(1)))
Func<string>
Func<U> Then<T, U>(this Func<T> t, Func<T, U> u)
{
return () => u (t ());
}
Func<string> Gpp3(string path, string id)
Func<string, string> Select(int idx)
Gpp3("bandLimits",freqClassUsage).Then(Select(0))
String (obviously) Enum Enum Func<string>
A("txOperationBandLowEdge" , F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Then(Select(0)))
A("txOperationBandHighEdge", F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Then(Select(1)))
Perfect?
Func<string> Gpp3(string path, string key)
{
return () =>
QueryContext.Instance.Gpp3Data.Get (path, key);
}
Func<QueryContext, T>
// When composing we lose the Context
Func<QueryContext, U> Then<T, U>(
this Func<QueryContext, T> t
, Func<T, U> u)
{
return ctx => u(t (ctx));
}
Down the rabbit hole...
type AttributeQuery<'T> = unit -> 'T
type AttributeQuery<'T> = QueryContext -> 'T
val gpp3: string -> string -> AttributeQuery<string>
val prodDataXml: string -> AttributeQuery<string>
val select: int -> string -> AttributeQuery<string>
// type AttributeQuery<'T> = QueryContext -> 'T
let gpp3 path key =
fun ctx -> ctx.Gpp3Data.Get path key
// type AttributeQuery<'T> = QueryContext -> 'T
let select idx s =
fun ctx ->
let vs = s.Split ','
vs.[idx] // TODO: error handling
//Gpp3("bandLimits",freqClassUsage).Then(Select(0))
gpp3 "bandLimits" freqClassUsage ??? select 0
val Bind:
AttributeQuery<'T>
-> ('T -> AttributeQuery<'U>)
-> AttributeQuery<'U>
val Return: 'T -> AttributeQuery<'T>
// type AttributeQuery<'T> = QueryContext -> 'T
let Return v =
fun ctx -> v
// type AttributeQuery<'T> = QueryContext -> 'T
let Bind firstq fsecondq =
fun ctx ->
let first = firstq ctx
let secondq = fsecondq first
let second = secondq ctx
second
let (>>=) firstq fsecondq = Bind firstq fsecondq
//Gpp3("bandLimits",freqClassUsage).Then(Select(0))
gpp3 "bandLimits" freqClassUsage >>= select 0
let bandLimits : AttributeQuery<string> =
gpp3 "bandLimits" freqClassUsage
let hello : AttributeQuery<string> =
select 0 "Hello,There"
let select0 : string -> AttributeQuery<string> =
select 0 // "Hello,There"
let q : AttributeQuery<string> =
bandLimits >>= select0
val Bind:
AttributeQuery<'T> // bandlimits
-> ('T -> AttributeQuery<'U>) // select0
-> AttributeQuery<'U>
val Return: 'T -> AttributeQuery<'T>
// type AttributeQuery<'T> = QueryContext -> 'T
let Bind firstq fsecondq =
fun ctx ->
let first = firstq ctx // bandlimits ctx
let secondq = fsecondq first // select0 first
let second = secondq ctx
second
//Gpp3("bandLimits",freqClassUsage).Then(Select(0))
gpp3 "bandLimits" freqClassUsage >>= select 0
Back to Kansas...
delegate T AttributeQuery<T> (QueryContext ctx);
AttributeQuery<T> Return<T> (T v)
{
return ctx => v;
}
AttributeQuery<U> Bind<T, U> (
this AttributeQuery<T> firstq
, Func<T, AttributeQuery<U>> fsecondq)
{
return ctx => {
var first = firstq (ctx);
var secondq = fsecondq (first);
var second = secondq (ctx);
return second;
};
}
public AttributeQuery<String> Gpp3(string path, string key);
public AttributeQuery<String> ProdDataXml(string path);
public Func<string, AttributeQuery<string>> Select(int idx);
Gpp3("bandLimits",freqClassUsage).Then(Select(0))
Gpp3("bandLimits",freqClassUsage).Bind(Select(0))
String (obviously) Enum Enum AttributeQuery<string>
A("txOperationBandLowEdge" , F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Bind(Select(0)))
A("txOperationBandHighEdge", F(kHz, kHz), Gpp3("bandLimits",freqClassUsage).Bind(Select(1)))
type AttributeQuery<'T> = QueryContext -> 'T
val Bind:
AttributeQuery<'T>
-> ('T -> AttributeQuery<'U>)
-> AttributeQuery<'U>
val Return: 'T -> AttributeQuery<'T>
Monad
“A monad is a monoid in the category of
endofunctors,
what's the problem?”
Philip Wadler
(Fake but funny)
// Monad type class
// https://wiki.haskell.org/Monad
type M<'T>
val Bind : M<'T> -> ('T -> M<'U>) -> M<'U>
val Return: 'T -> M<'T>
// Monad laws
// https://wiki.haskell.org/Monad_laws
let (>=>) t u = fun v -> Bind (t v) u
Left identity : Return >=> g ≡ g
Right identity: f >=> Return ≡ f
Associativity :
(f >=> g) >=> h
≡
f >=> (g >=> h)
Left identity : x + 0 ≡ x
Right identity: 0 + x ≡ x
Associativity : (x + y) + z ≡ x + (y + z)
The Essence of Monad
”The essence of monad is thus 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).“
https://wiki.haskell.org/Monad
Monads are useful
 We like to define a query to an attribute
 Query implies separation between composition and
execution
 We don’t want to our query to rely on singletons
 Makes testing and composition (if effectful) difficult
 No singletons implies an extra data
 This is the essence of Monads
Experimentation leads to understanding
Common usages for Monads
 Coroutines
 Environment state
 Parsers
 Rules
 Queries
 Tracing
 Transformers
https://github.com/mrange/presentations/
fsharp/ce/turtle
http://www.slideshare.net/martenrange/
monad-a-functional-design-pattern
Questions?

More Related Content

What's hot

Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
Mike Fogus
 

What's hot (20)

Deep Learning with Julia1.0 and Flux
Deep Learning with Julia1.0 and FluxDeep Learning with Julia1.0 and Flux
Deep Learning with Julia1.0 and Flux
 
SevillaR meetup: dplyr and magrittr
SevillaR meetup: dplyr and magrittrSevillaR meetup: dplyr and magrittr
SevillaR meetup: dplyr and magrittr
 
Профилирование и оптимизация производительности Ruby-кода
Профилирование и оптимизация производительности Ruby-кодаПрофилирование и оптимизация производительности Ruby-кода
Профилирование и оптимизация производительности Ruby-кода
 
user2015 keynote talk
user2015 keynote talkuser2015 keynote talk
user2015 keynote talk
 
Modular Macros for OCaml
Modular Macros for OCamlModular Macros for OCaml
Modular Macros for OCaml
 
MongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The Cloud
MongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The CloudMongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The Cloud
MongoDB World 2019: Event Horizon: Meet Albert Einstein As You Move To The Cloud
 
Introduction to jRuby
Introduction to jRubyIntroduction to jRuby
Introduction to jRuby
 
Documento de acrobat2
Documento de acrobat2Documento de acrobat2
Documento de acrobat2
 
The Ring programming language version 1.5.1 book - Part 44 of 180
The Ring programming language version 1.5.1 book - Part 44 of 180The Ring programming language version 1.5.1 book - Part 44 of 180
The Ring programming language version 1.5.1 book - Part 44 of 180
 
Rust Synchronization Primitives
Rust Synchronization PrimitivesRust Synchronization Primitives
Rust Synchronization Primitives
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
 
Python hmm
Python hmmPython hmm
Python hmm
 
Engineering fast indexes
Engineering fast indexesEngineering fast indexes
Engineering fast indexes
 
Parallel Computing in R
Parallel Computing in RParallel Computing in R
Parallel Computing in R
 
Building HTML5 enabled web applications with Visual Studio 2011
Building HTML5 enabled web applications with Visual Studio 2011 Building HTML5 enabled web applications with Visual Studio 2011
Building HTML5 enabled web applications with Visual Studio 2011
 
Prgišče Lispa
Prgišče LispaPrgišče Lispa
Prgišče Lispa
 
Hadoop in a Box
Hadoop in a BoxHadoop in a Box
Hadoop in a Box
 
Grand centraldispatch
Grand centraldispatchGrand centraldispatch
Grand centraldispatch
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
 
The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212
 

Viewers also liked (8)

Formlets
FormletsFormlets
Formlets
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Concurrency - responsiveness in .NET
Concurrency - responsiveness in .NETConcurrency - responsiveness in .NET
Concurrency - responsiveness in .NET
 
Meta Programming
Meta ProgrammingMeta Programming
Meta Programming
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogramming
 
Monad as things to do
Monad as things to doMonad as things to do
Monad as things to do
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
Monad Transformers In The Wild
Monad Transformers In The WildMonad Transformers In The Wild
Monad Transformers In The Wild
 

Similar to Monad - a functional design pattern

Similar to Monad - a functional design pattern (20)

Simple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorialSimple, fast, and scalable torch7 tutorial
Simple, fast, and scalable torch7 tutorial
 
SICP勉強会について
SICP勉強会についてSICP勉強会について
SICP勉強会について
 
The Ring programming language version 1.8 book - Part 42 of 202
The Ring programming language version 1.8 book - Part 42 of 202The Ring programming language version 1.8 book - Part 42 of 202
The Ring programming language version 1.8 book - Part 42 of 202
 
The Ring programming language version 1.9 book - Part 45 of 210
The Ring programming language version 1.9 book - Part 45 of 210The Ring programming language version 1.9 book - Part 45 of 210
The Ring programming language version 1.9 book - Part 45 of 210
 
Advanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part IIAdvanced Data Visualization Examples with R-Part II
Advanced Data Visualization Examples with R-Part II
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
Coq for ML users
Coq for ML usersCoq for ML users
Coq for ML users
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
Swift study: Closure
Swift study: ClosureSwift study: Closure
Swift study: Closure
 
Time Series Analysis and Mining with R
Time Series Analysis and Mining with RTime Series Analysis and Mining with R
Time Series Analysis and Mining with R
 
CLUSTERGRAM
CLUSTERGRAMCLUSTERGRAM
CLUSTERGRAM
 
PyData Paris 2015 - Track 1.1 Alexandre Gramfort
PyData Paris 2015 - Track 1.1 Alexandre GramfortPyData Paris 2015 - Track 1.1 Alexandre Gramfort
PyData Paris 2015 - Track 1.1 Alexandre Gramfort
 
C PROGRAMS - SARASWATHI RAMALINGAM
C PROGRAMS - SARASWATHI RAMALINGAMC PROGRAMS - SARASWATHI RAMALINGAM
C PROGRAMS - SARASWATHI RAMALINGAM
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made Simple
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
 
codecentric AG: Using Cassandra and Clojure for Data Crunching backends
codecentric AG: Using Cassandra and Clojure for Data Crunching backendscodecentric AG: Using Cassandra and Clojure for Data Crunching backends
codecentric AG: Using Cassandra and Clojure for Data Crunching backends
 
The Ring programming language version 1.5.4 book - Part 25 of 185
The Ring programming language version 1.5.4 book - Part 25 of 185The Ring programming language version 1.5.4 book - Part 25 of 185
The Ring programming language version 1.5.4 book - Part 25 of 185
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 

Monad - a functional design pattern