SlideShare ist ein Scribd-Unternehmen logo
1 von 81
Downloaden Sie, um offline zu lesen
Functional Patterns in 
Domain Modeling 
with examples from the Financial Domain 
@debasishg 
https://github.com/debasishg 
http://debasishg.blogspot.com 
Wednesday, 5 November 14
What is a domain model ? 
A domain model in problem solving and software engineering is a 
conceptual model of all the topics related to a specific problem. It 
describes the various entities, their attributes, roles, and 
relationships, plus the constraints that govern the problem domain. 
It does not describe the solutions to the problem. 
Wikipedia (http://en.wikipedia.org/wiki/Domain_model) 
Wednesday, 5 November 14
Rich domain 
models 
State Behavior 
Class 
• Class models the domain abstraction 
• Contains both the state and the 
behavior together 
• State hidden within private access 
specifier for fear of being mutated 
inadvertently 
• Decision to take - what should go inside 
a class ? 
• Decision to take - where do we put 
behaviors that involve multiple classes ? 
Often led to bloated service classes 
State Behavior 
Wednesday, 5 November 14
• Algebraic Data Type (ADT) models the 
domain abstraction 
• Contains only the defining state as 
immutable values 
• No need to make things “private” since 
we are talking about immutable values 
• Nothing but the bare essential 
definitions go inside an ADT 
• All behaviors are outside the ADT in 
modules as functions that define the 
domain behaviors 
Lean domain 
models 
Immutable 
State 
Behavior 
Immutable 
State 
Behavior 
Algebraic Data Types Functions in modules 
Wednesday, 5 November 14
Rich domain 
models 
State Behavior 
Class 
• We start with the class design 
• Make it sufficiently “rich” by putting all 
related behaviors within the class, used to 
call them fine grained abstractions 
• We put larger behaviors in the form of 
services (aka managers) and used to call 
them coarse grained abstractions 
State Behavior 
Wednesday, 5 November 14
Lean domain 
models 
Immutable 
State 
Behavior 
• We start with the functions, the 
behaviors of the domain 
• We define function algebras using types 
that don’t have any implementation yet 
(we will see examples shortly) 
• Primary focus is on compositionality that 
enables building larger functions out of 
smaller ones 
• Functions reside in modules which also 
compose 
• Entities are built with algebraic data 
types that implement the types we used in 
defining the functions 
Immutable 
State 
Behavior 
Algebraic Data Types Functions in modules 
Wednesday, 5 November 14
Wednesday, 5 November 14
Domain Model 
Elements 
• Entities & Value Objects - modeled with 
types 
• Behaviors - modeled with functions 
• Domain rules - expressed as constraints 
& validations 
• Bounded Context - delineates 
subsystems within the model 
• Ubiquitous Language 
Wednesday, 5 November 14
.. and some Patterns 
• Domain object lifecycle patterns 
Aggregates - encapsulate object 
references 
Factories - abstract object creation & 
management 
Repositories - manage object persistence 
& queries 
Wednesday, 5 November 14
.. some more Patterns 
• Refactoring patterns 
Making implicit concepts explicit 
Intention revealing interfaces 
Side-effect free functions 
Declarative design 
Specification for validation 
Wednesday, 5 November 14
The Functional Lens .. 
Wednesday, 5 November 14
Why Functional ? 
• Ability to reason about your code - virtues 
of being pure & referentially transparent 
• Increased modularity - clean separation of 
state and behavior 
• Immutable data structures 
• Concurrency 
Wednesday, 5 November 14
Problem Domain 
Wednesday, 5 November 14
Bank 
Account 
Trade 
Customer 
... 
... 
... 
Problem Domain 
... 
entities 
Wednesday, 5 November 14
place 
order Problem Domain 
Bank 
Account 
Trade 
Customer 
... 
... 
... 
do trade 
process 
execution 
... 
entities 
behaviors 
Wednesday, 5 November 14
place 
order Problem Domain 
Bank 
Account 
Trade 
Customer 
... 
... 
... 
do trade 
process 
execution 
... 
market 
regulations 
tax laws 
brokerage 
commission 
rates ... 
entities 
behaviors 
laws 
Wednesday, 5 November 14
place 
order Problem Domain 
Bank 
Account 
Trade 
Customer 
... 
... 
... 
do trade 
process 
execution 
... 
market 
regulations 
tax laws 
brokerage 
commission 
rates ... 
entities 
behaviors 
laws 
Wednesday, 5 November 14
place 
order Problem Domain 
Solution Domain 
behaviors • Functions 
do trade 
process 
execution 
... 
• On Types 
• Constraints 
Wednesday, 5 November 14
place 
order Problem Domain 
Solution Domain 
behaviors • Functions 
do trade 
process 
execution 
... 
• On Types 
• Constraints 
Algebra 
• Morphisms 
• Sets 
• Laws 
Wednesday, 5 November 14
place 
order Problem Domain 
Solution Domain 
behaviors • Functions 
do trade 
process 
execution 
... 
• On Types 
• Constraints 
Algebra 
• Morphisms 
• Sets 
• Laws 
Compose for larger abstractions 
Wednesday, 5 November 14
A Monoid 
An algebraic structure 
having 
• an identity element 
• a binary associative 
operation 
trait Monoid[A] { 
def zero: A 
def op(l: A, r: => A): A 
} 
object MonoidLaws { 
def associative[A: Equal: Monoid] 
(a1: A, a2: A, a3: A): Boolean = //.. 
def rightIdentity[A: Equal: Monoid] 
(a: A) = //.. 
def leftIdentity[A: Equal: Monoid] 
(a: A) = //.. 
} 
Wednesday, 5 November 14
Monoid Laws 
An algebraic structure 
havingsa 
• an identity element 
• a binary associative 
operation 
trait Monoid[A] { 
def zero: A 
def op(l: A, r: => A): A 
} 
object MonoidLaws { 
def associative[A: Equal: Monoid] 
(a1: A, a2: A, a3: A): Boolean = //.. 
def rightIdentity[A: Equal: Monoid] 
(a: A) = //.. 
def leftIdentity[A: Equal: Monoid] 
(a: A) = //.. 
} 
satisfies 
op(x, zero) == x and op(zero, x) == x 
satisfies 
op(op(x, y), z) == op(x, op(y, z)) 
Wednesday, 5 November 14
.. and we talk about domain algebra, where the 
domain entities are implemented with sets of 
types and domain behaviors are functions that 
map a type to one or more types. And 
domain rules are the laws which define the 
constraints of the business .. 
Wednesday, 5 November 14
Pattern #1: Functional Modeling encourages Algebraic API 
Design which leads to organic evolution of domain 
models 
Wednesday, 5 November 14
Client places order 
- flexible format 
1 
Wednesday, 5 November 14
Client places order 
- flexible format 
1 2 
Transform to internal domain 
model entity and place for execution 
Wednesday, 5 November 14
Client places order 
- flexible format 
1 2 
Transform to internal domain 
model entity and place for execution 
Trade & Allocate to 
client accounts 
3 
Wednesday, 5 November 14
def clientOrders: ClientOrderSheet => List[Order] 
def execute: Market => Account => Order => List[Execution] 
def allocate: List[Account] => Execution => List[Trade] 
Wednesday, 5 November 14
Types out of thin air No implementation till now 
def clientOrders: ClientOrderSheet => List[Order] 
def execute: Market => Account => Order => List[Execution] 
def allocate: List[Account] => Execution => List[Trade] 
Wednesday, 5 November 14
Types out of thin air No implementation till now 
def clientOrders: ClientOrderSheet => List[Order] 
def execute: Market => Account => Order => List[Execution] 
def allocate: List[Account] => Execution => List[Trade] 
Just some types & operations on those types 
+ 
some laws governing those operations 
Wednesday, 5 November 14
Types out of thin air No implementation till now 
def clientOrders: ClientOrderSheet => List[Order] 
Algebra of the API 
def execute: Market => Account => Order => List[Execution] 
def allocate: List[Account] => Execution => List[Trade] 
Just some types & operations on those types 
+ 
some laws governing those operations 
Wednesday, 5 November 14
Algebraic Design 
• The algebra is the binding contract of the 
API 
• Implementation is NOT part of the algebra 
• An algebra can have multiple interpreters 
(aka implementations) 
• The core principle of functional 
programming is to decouple the algebra from 
the interpreter 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: ClientOrderSheet => List[Order] 
def execute: Market => Account => Order => List[Execution] 
def allocate: List[Account] => Execution => List[Trade] 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: ClientOrderSheet => List[Order] 
def execute(m: Market, broker: Account): Order => List[Execution] 
def allocate(accounts: List[Account]): Execution => List[Trade] 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: ClientOrderSheet => List[Order] 
def execute(m: Market, broker: Account): Order => List[Execution] 
def allocate(accounts: List[Account]): Execution => List[Trade] 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: ClientOrderSheet => List[Order] 
def execute(m: Market, broker: Account): Order => List[Execution] 
def allocate(accounts: List[Account]): Execution => List[Trade] 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: ClientOrderSheet => List[Order] 
def execute(m: Market, broker: Account): Order => List[Execution] 
def allocate(accounts: List[Account]): Execution => List[Trade] 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: ClientOrderSheet => List[Order] 
def execute(m: Market, broker: Account): Order => List[Execution] 
def allocate(accounts: List[Account]): Execution => List[Trade] 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: ClientOrderSheet => List[Order] 
def execute(m: Market, broker: Account): Order => List[Execution] 
def allocate(accounts: List[Account]): Execution => List[Trade] 
Function Composition with Effects 
Wednesday, 5 November 14
let’s mine some 
def clientOrders: ClientOrderSheet => List[Order] 
def execute(m: Market, broker: Account): Order => List[Execution] 
def allocate(accounts: List[Account]): Execution => List[Trade] 
It’s a Kleisli ! 
patterns .. 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def clientOrders: Kleisli[List, ClientOrderSheet, Order] 
def execute(m: Market, b: Account): Kleisli[List, Order, Execution] 
def allocate(acts: List[Account]): Kleisli[List, Execution, Trade] 
Follow the types 
Wednesday, 5 November 14
let’s mine some 
patterns .. 
def tradeGeneration( 
market: Market, 
broker: Account, 
clientAccounts: List[Account]) = { 
clientOrders andThen 
execute(market, broker) andThen 
allocate(clientAccounts) 
} 
Implementation follows the specification 
Wednesday, 5 November 14
def tradeGeneration( 
market: Market, 
broker: Account, 
clientAccounts: List[Account]) = { 
clientOrders andThen 
execute(market, broker) andThen 
allocate(clientAccounts) 
} 
Implementation follows the specification 
and we get the Ubiquitous Language for 
free :-) 
let’s mine some 
patterns .. 
Wednesday, 5 November 14
Nouns first ? Really ? 
Wednesday, 5 November 14
Just as the doctor 
ordered .. 
✓Making implicit concepts 
explicit 
✓Intention revealing 
interfaces 
✓Side-effect free functions 
✓Declarative design 
Wednesday, 5 November 14
Just as the doctor 
ordered .. 
✓types as the 
Making implicit functions concepts 
& explicit 
patterns for 
on 
Claim: With these ✓glue we get all based binding Intention generic revealing 
abstractions free using function composition 
interfaces 
✓Side-effect free functions 
✓Declarative design 
Wednesday, 5 November 14
Pattern #2: DDD patterns like Factories & Specification 
are part of the normal idioms of functional programming 
Wednesday, 5 November 14
/** 
* allocates an execution to a List of client accounts 
* generates a List of trades 
*/ 
def allocate(accounts: List[Account]): Kleisli[List, Execution, Trade] = 
kleisli { execution => 
accounts.map { account => 
makeTrade(account, 
execution.instrument, 
genRef(), 
execution.market, 
execution.unitPrice, 
execution.quantity / accounts.size 
) 
} 
} 
Wednesday, 5 November 14
/** 
* allocates an execution to a List of client accounts 
* generates a List of trades 
*/ 
def allocate(accounts: List[Account]): Kleisli[List, Execution, Trade] = 
kleisli { execution => 
accounts.map { account => 
makeTrade(account, 
execution.instrument, 
genRef(), 
execution.market, 
execution.unitPrice, 
execution.quantity / accounts.size 
) 
} 
} 
Wednesday, 5 November 14
/** 
* allocates an execution to a List of client accounts 
* generates a List of trades 
*/ 
def allocate(accounts: List[Account]): Kleisli[List, Execution, Trade] = 
kleisli { execution => 
accounts.map { account => 
makeTrade(account, 
execution.instrument, 
genRef(), 
execution.market, 
execution.unitPrice, 
execution.quantity / accounts.size 
) 
} 
} 
Makes a Trade out of the 
parameters passed 
What about validations ? 
How do we handle failures ? 
Wednesday, 5 November 14
case class Trade (account: Account, 
instrument: Instrument, 
refNo: String, 
market: Market, 
unitPrice: BigDecimal, 
quantity: BigDecimal, 
tradeDate: Date = today, 
valueDate: Option[Date] = None, 
taxFees: Option[List[(TaxFeeId, BigDecimal)]] = None, 
netAmount: Option[BigDecimal] = None 
) 
Wednesday, 5 November 14
must be > 0 
case class Trade (account: Account, 
instrument: Instrument, 
refNo: String, 
market: Market, 
unitPrice: BigDecimal, 
quantity: BigDecimal, 
tradeDate: Date = today, 
valueDate: Option[Date] = None, 
taxFees: Option[List[(TaxFeeId, BigDecimal)]] = None, 
netAmount: Option[BigDecimal] = None 
) 
must be > trade date 
Wednesday, 5 November 14
Monads .. 
Wednesday, 5 November 14
monadic validation pattern 
def makeTrade(account: Account, 
instrument: Instrument, 
refNo: String, 
market: Market, 
unitPrice: BigDecimal, 
quantity: BigDecimal, 
td: Date = today, 
vd: Option[Date] = None): ValidationStatus[Trade] = { 
val trd = Trade(account, instrument, refNo, 
market, unitPrice, quantity, td, vd) 
val s = for { 
_ <- validQuantity 
_ <- validValueDate 
t <- validUnitPrice 
} yield t 
s(trd) 
} 
Wednesday, 5 November 14
monadic validation pattern 
def makeTrade(account: Account, 
instrument: Instrument, 
refNo: String, 
market: Market, 
unitPrice: BigDecimal, 
quantity: BigDecimal, 
td: Date = today, 
vd: Option[Date] = None): ValidationStatus[Trade] = { 
val trd = Trade(account, instrument, refNo, 
market, unitPrice, quantity, td, vd) 
val s = for { 
_ <- validQuantity 
_ <- validValueDate 
t <- validUnitPrice 
} yield t 
s(trd) 
} 
(monad 
comprehension) 
Wednesday, 5 November 14
monadic validation pattern 
Smart Constructor : The 
def makeTrade(account: Account, 
instrument: Instrument, 
refNo: String, 
market: Market, 
unitPrice: BigDecimal, 
quantity: BigDecimal, 
td: Date = today, 
vd: Option[Date] = None): ValidationStatus[Trade] = { 
val trd = Trade(account, instrument, refNo, 
Factory Pattern 
(Chapter 6) 
market, unitPrice, quantity, td, vd) 
val s = for { 
_ <- validQuantity 
_ <- validValueDate 
t <- validUnitPrice 
} yield t 
s(trd) 
} 
The Specification 
Pattern 
(Chapter 9) 
Wednesday, 5 November 14
let’s mine some more 
patterns (with types) .. disjunction type (a sum 
type ValidationStatus[S] = /[String, S] 
type ReaderTStatus[A, S] = ReaderT[ValidationStatus, A, S] 
object ReaderTStatus extends KleisliInstances with KleisliFunctions { 
def apply[A, S](f: A => ValidationStatus[S]): ReaderTStatus[A, S] 
= kleisli(f) 
} 
type) : either a valid object or a 
failure message 
monad transformer 
Wednesday, 5 November 14
monadic validation 
pattern .. 
def validQuantity = ReaderTStatus[Trade, Trade] { trade => 
if (trade.quantity < 0) 
left(s"Quantity needs to be > 0 for $trade") 
else right(trade) 
} 
def validUnitPrice = ReaderTStatus[Trade, Trade] { trade => 
if (trade.unitPrice < 0) 
left(s"Unit Price needs to be > 0 for $trade") 
else right(trade) 
} 
def validValueDate = ReaderTStatus[Trade, Trade] { trade => 
trade.valueDate.map(vd => 
if (trade.tradeDate after vd) 
left(s"Trade Date ${trade.tradeDate} must be before value date $vd") 
else right(trade) 
).getOrElse(right(trade)) 
} 
Wednesday, 5 November 14
With Functional 
Programming 
• we implement all specific patterns in terms 
of generic abstractions 
• all these generic abstractions are based on 
function composition 
• and encourage immutability & referential 
transparency 
Wednesday, 5 November 14
Pattern #3: Functional Modeling encourages 
parametricity, i.e. abstract logic from specific types to 
generic ones 
Wednesday, 5 November 14
case class Trade( 
refNo: String, 
instrument: Instrument, 
tradeDate: Date, 
valueDate: Date, 
principal: Money, 
taxes: List[Tax], 
... 
) 
Wednesday, 5 November 14
case class Trade( 
refNo: String, 
instrument: Instrument, 
tradeDate: Date, 
valueDate: Date, 
principal: Money, 
taxes: List[Tax], 
... 
) 
case class Money(amount: BigDecimal, ccy: Currency) { 
def +(m: Money) = { 
sealed trait Currency 
case object USD extends Currency 
case object AUD extends Currency 
case object SGD extends Currency 
case object INR extends Currency 
require(m.ccy == ccy) 
Money(amount + m.amount, ccy) 
} 
def >(m: Money) = { 
require(m.ccy == ccy) 
if (amount > m.amount) this else m 
} 
} 
Wednesday, 5 November 14
case class Trade( 
refNo: String, 
instrument: Instrument, 
tradeDate: Date, 
valueDate: Date, 
principal: Money, 
taxes: List[Tax], 
... 
) 
def netValue: Trade => Money = //.. 
Given a list of trades, find the total net valuation of all trades 
in base currency 
Wednesday, 5 November 14
def inBaseCcy: Money => Money = //.. 
def valueTradesInBaseCcy(ts: List[Trade]) = { 
ts.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc + inBaseCcy(netValue(e)) 
} 
} 
Wednesday, 5 November 14
case class Transaction(id: String, value: Money) 
Given a list of transactions for a customer, find the highest 
valued transaction 
Wednesday, 5 November 14
case class Transaction(id: String, value: Money) 
def highestValueTxn(txns: List[Transaction]) = { 
txns.foldLeft(Money(0, baseCcy)) { (acc, e) => 
Given a list of transactions for a customer, find the highest 
valued transaction 
acc > e.value 
} 
} 
Wednesday, 5 November 14
fold on the collection 
def valueTradesInBaseCcy(ts: List[Trade]) = { 
ts.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc + inBaseCcy(netValue(e)) 
} 
} 
def highestValueTxn(txns: List[Transaction]) = { 
txns.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc > e.value 
} 
} 
Wednesday, 5 November 14
zero on Money 
associative binary 
operation on Money 
def valueTradesInBaseCcy(ts: List[Trade]) = { 
ts.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc + inBaseCcy(netValue(e)) 
} 
} 
def highestValueTxn(txns: List[Transaction]) = { 
txns.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc > e.value 
} 
} 
Wednesday, 5 November 14
Instead of the specific collection type (List), we 
can abstract over the type constructor using 
the more general Foldable 
def valueTradesInBaseCcy(ts: List[Trade]) = { 
ts.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc + inBaseCcy(netValue(e)) 
} 
} 
def highestValueTxn(txns: List[Transaction]) = { 
txns.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc > e.value 
} 
} 
Wednesday, 5 November 14
look ma .. Monoid for Money ! 
def valueTradesInBaseCcy(ts: List[Trade]) = { 
ts.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc + inBaseCcy(netValue(e)) 
} 
} 
def highestValueTxn(txns: List[Transaction]) = { 
txns.foldLeft(Money(0, baseCcy)) { (acc, e) => 
acc > e.value 
} 
} 
Wednesday, 5 November 14
fold the collection on a monoid 
Foldable abstracts over 
the type constructor 
Monoid abstracts over 
the operation 
Wednesday, 5 November 14
def mapReduce[F[_], A, B](as: F[A])(f: A => B) 
(implicit fd: Foldable[F], m: Monoid[B]) = fd.foldMap(as)(f) 
Wednesday, 5 November 14
def mapReduce[F[_], A, B](as: F[A])(f: A => B) 
(implicit fd: Foldable[F], m: Monoid[B]) = fd.foldMap(as)(f) 
def valueTradesInBaseCcy(ts: List[Trade]) = 
mapReduce(ts)(netValue andThen inBaseCcy) 
def highestValueTxn(txns: List[Transaction]) = 
mapReduce(txns)(_.value) 
Wednesday, 5 November 14
trait Foldable[F[_]] { 
def foldl[A, B](as: F[A], z: B, f: (B, A) => B): B 
def foldMap[A, B](as: F[A], f: A => B)(implicit m: Monoid[B]): B = 
foldl(as, m.zero, (b: B, a: A) => m.add(b, f(a))) 
} 
implicit val listFoldable = new Foldable[List] { 
def foldl[A, B](as: List[A], z: B, f: (B, A) => B) = as.foldLeft(z)(f) 
} 
Wednesday, 5 November 14
implicit def MoneyMonoid(implicit c: Currency) = 
new Monoid[Money] { 
def zero: Money = Money(BigDecimal(0), c) 
def append(m1: Money, m2: => Money) = m1 + m2 
} 
implicit def MaxMoneyMonoid(implicit c: Currency) = 
new Monoid[Money] { 
def zero: Money = Money(BigDecimal(0), c) 
def append(m1: Money, m2: => Money) = m1 > m2 
} 
Wednesday, 5 November 14
def mapReduce[F[_], A, B](as: F[A])(f: A => B) 
(implicit fd: Foldable[F], m: Monoid[B]) = fd.foldMap(as)(f) 
def valueTradesInBaseCcy(ts: List[Trade]) = 
mapReduce(ts)(netValue andThen inBaseCcy) 
def highestValueTxn(txns: List[Transaction]) = 
mapReduce(txns)(_.value) 
This last pattern is inspired from Runar’s response on this SoF thread http://stackoverflow.com/questions/4765532/what-does-abstract-over-mean 
Wednesday, 5 November 14
Takeaways .. 
• Moves the algebra from domain specific 
abstractions to more generic ones 
• The program space in the mapReduce 
function is shrunk - so scope of error is 
reduced 
• Increases the parametricity of our program 
- mapReduce is now parametric in type 
parameters A and B (for all A and B) 
Wednesday, 5 November 14
When using functional modeling, always try to express 
domain specific abstractions and behaviors in terms of more 
generic, lawful abstractions. Doing this you make your 
functions more generic, more usable in a broader context 
and yet simpler to comprehend. 
This is the concept of parametricity and is one of the 
Wednesday, 5 November 14
Use code “mlghosh2” for a 50% discount 
Wednesday, 5 November 14
Image 
acknowledgements 
• www.valuewalk.com 
• http://bienabee.com 
• http://www.ownta.com 
• http://ebay.in 
• http://www.clker.com 
• http://homepages.inf.ed.ac.uk/wadler/ 
• http://en.wikipedia.org 
Wednesday, 5 November 14
Thank You! 
Wednesday, 5 November 14

Más contenido relacionado

Was ist angesagt?

Functional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayFunctional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersPiotr Paradziński
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of AlgorithmsSwapnil Agrawal
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedis Labs
 
Expert system with python -2
Expert system with python  -2Expert system with python  -2
Expert system with python -2Ahmad Hussein
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
 
Jarrar: Description Logic
Jarrar: Description LogicJarrar: Description Logic
Jarrar: Description LogicMustafa Jarrar
 
Dimensionality Reduction
Dimensionality ReductionDimensionality Reduction
Dimensionality ReductionSaad Elbeleidy
 
Peeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdfPeeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdfJaroslavRegec1
 
Machine learning basics using trees algorithm (Random forest, Gradient Boosting)
Machine learning basics using trees algorithm (Random forest, Gradient Boosting)Machine learning basics using trees algorithm (Random forest, Gradient Boosting)
Machine learning basics using trees algorithm (Random forest, Gradient Boosting)Parth Khare
 
Big Data Architecture
Big Data ArchitectureBig Data Architecture
Big Data ArchitectureGuido Schmutz
 
Hands on Optimization in Python (1).pptx
Hands on Optimization in Python (1).pptxHands on Optimization in Python (1).pptx
Hands on Optimization in Python (1).pptxASHISHJANGID38
 
Wrapper feature selection method
Wrapper feature selection methodWrapper feature selection method
Wrapper feature selection methodAmir Razmjou
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of AlgorithmsArvind Krishnaa
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming languageVasavi College of Engg
 
Overfitting & Underfitting
Overfitting & UnderfittingOverfitting & Underfitting
Overfitting & UnderfittingSOUMIT KAR
 
Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...
Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...
Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...PAPIs.io
 

Was ist angesagt? (20)

Functional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayFunctional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 Way
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly matters
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis GraphRedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
RedisConf18 - Lower Latency Graph Queries in Cypher with Redis Graph
 
Expert system with python -2
Expert system with python  -2Expert system with python  -2
Expert system with python -2
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
Jarrar: Description Logic
Jarrar: Description LogicJarrar: Description Logic
Jarrar: Description Logic
 
Dimensionality Reduction
Dimensionality ReductionDimensionality Reduction
Dimensionality Reduction
 
Peeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdfPeeking inside the engine of ZIO SQL.pdf
Peeking inside the engine of ZIO SQL.pdf
 
Kleisli Composition
Kleisli CompositionKleisli Composition
Kleisli Composition
 
Machine learning basics using trees algorithm (Random forest, Gradient Boosting)
Machine learning basics using trees algorithm (Random forest, Gradient Boosting)Machine learning basics using trees algorithm (Random forest, Gradient Boosting)
Machine learning basics using trees algorithm (Random forest, Gradient Boosting)
 
Big Data Architecture
Big Data ArchitectureBig Data Architecture
Big Data Architecture
 
Hands on Optimization in Python (1).pptx
Hands on Optimization in Python (1).pptxHands on Optimization in Python (1).pptx
Hands on Optimization in Python (1).pptx
 
Wrapper feature selection method
Wrapper feature selection methodWrapper feature selection method
Wrapper feature selection method
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 
Overfitting & Underfitting
Overfitting & UnderfittingOverfitting & Underfitting
Overfitting & Underfitting
 
Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...
Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...
Machine Learning Performance Evaluation: Tips and Pitfalls - Jose Hernandez O...
 

Andere mochten auch

From functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modelingFrom functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modelingDebasish Ghosh
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingDebasish Ghosh
 
Domain-driven design
Domain-driven designDomain-driven design
Domain-driven designKnoldus Inc.
 
An Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain ModelingAn Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain ModelingDebasish Ghosh
 
I_ITSEC_2013_-_LTEC_paper
I_ITSEC_2013_-_LTEC_paperI_ITSEC_2013_-_LTEC_paper
I_ITSEC_2013_-_LTEC_paperBrian Lichtman
 
Dutch tax budget 2012 cooperative and substantial interest
Dutch tax budget 2012 cooperative and substantial interestDutch tax budget 2012 cooperative and substantial interest
Dutch tax budget 2012 cooperative and substantial interestPaul van den Tillaart
 
Improving Findability through Mashups and Visualizations.
Improving Findability through Mashups and Visualizations.Improving Findability through Mashups and Visualizations.
Improving Findability through Mashups and Visualizations.Sten Govaerts
 
Caratula del deber 2
Caratula del deber 2Caratula del deber 2
Caratula del deber 2karen210
 
Trend One(Portfolio) November 2008
Trend One(Portfolio) November 2008Trend One(Portfolio) November 2008
Trend One(Portfolio) November 2008rwtrend
 
Juego empresarial jovenes emprendedores
Juego empresarial    jovenes emprendedoresJuego empresarial    jovenes emprendedores
Juego empresarial jovenes emprendedoresOpcionesTecnicas
 
Catálogo Disneyland Paris, producto Orizonia life
Catálogo Disneyland Paris, producto Orizonia lifeCatálogo Disneyland Paris, producto Orizonia life
Catálogo Disneyland Paris, producto Orizonia lifeOrizonialife
 
Clases Scrollbar,Scrollpane,Choice
Clases Scrollbar,Scrollpane,ChoiceClases Scrollbar,Scrollpane,Choice
Clases Scrollbar,Scrollpane,ChoiceKathya Martinez
 
Danza clásica definitivo
Danza clásica definitivoDanza clásica definitivo
Danza clásica definitivoaaradica
 

Andere mochten auch (20)

From functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modelingFrom functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modeling
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
 
Domain-driven design
Domain-driven designDomain-driven design
Domain-driven design
 
An Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain ModelingAn Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain Modeling
 
I_ITSEC_2013_-_LTEC_paper
I_ITSEC_2013_-_LTEC_paperI_ITSEC_2013_-_LTEC_paper
I_ITSEC_2013_-_LTEC_paper
 
Dutch tax budget 2012 cooperative and substantial interest
Dutch tax budget 2012 cooperative and substantial interestDutch tax budget 2012 cooperative and substantial interest
Dutch tax budget 2012 cooperative and substantial interest
 
Improving Findability through Mashups and Visualizations.
Improving Findability through Mashups and Visualizations.Improving Findability through Mashups and Visualizations.
Improving Findability through Mashups and Visualizations.
 
Caratula del deber 2
Caratula del deber 2Caratula del deber 2
Caratula del deber 2
 
Trend One(Portfolio) November 2008
Trend One(Portfolio) November 2008Trend One(Portfolio) November 2008
Trend One(Portfolio) November 2008
 
Juego empresarial jovenes emprendedores
Juego empresarial    jovenes emprendedoresJuego empresarial    jovenes emprendedores
Juego empresarial jovenes emprendedores
 
La explosion de Cadiz
La explosion de CadizLa explosion de Cadiz
La explosion de Cadiz
 
Baigiang elearning
Baigiang elearningBaigiang elearning
Baigiang elearning
 
Easy-Protect-Plan-Brochure
Easy-Protect-Plan-BrochureEasy-Protect-Plan-Brochure
Easy-Protect-Plan-Brochure
 
O obvio
O obvioO obvio
O obvio
 
Catálogo Disneyland Paris, producto Orizonia life
Catálogo Disneyland Paris, producto Orizonia lifeCatálogo Disneyland Paris, producto Orizonia life
Catálogo Disneyland Paris, producto Orizonia life
 
Patologia quirurgica
Patologia quirurgicaPatologia quirurgica
Patologia quirurgica
 
Clases Scrollbar,Scrollpane,Choice
Clases Scrollbar,Scrollpane,ChoiceClases Scrollbar,Scrollpane,Choice
Clases Scrollbar,Scrollpane,Choice
 
Catalogo WorkNC Dental
Catalogo WorkNC DentalCatalogo WorkNC Dental
Catalogo WorkNC Dental
 
Viruela infectologia
Viruela infectologiaViruela infectologia
Viruela infectologia
 
Danza clásica definitivo
Danza clásica definitivoDanza clásica definitivo
Danza clásica definitivo
 

Ähnlich wie Functional Patterns in Domain Modeling

Domain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approachDomain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approachDebasish Ghosh
 
Functional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modelingFunctional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modelingDebasish Ghosh
 
Architectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsArchitectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsDebasish Ghosh
 
Modelling a complex domain with Domain-Driven Design
Modelling a complex domain with Domain-Driven DesignModelling a complex domain with Domain-Driven Design
Modelling a complex domain with Domain-Driven DesignNaeem Sarfraz
 
Everything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus scriptEverything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus scriptBill Buchan
 
The Data Architect Manifesto
The Data Architect ManifestoThe Data Architect Manifesto
The Data Architect ManifestoMahesh Vallampati
 
Starring sakila my sql university 2009
Starring sakila my sql university 2009Starring sakila my sql university 2009
Starring sakila my sql university 2009David Paz
 
Practical Ontology For Enterprise Data Management
Practical Ontology For Enterprise Data ManagementPractical Ontology For Enterprise Data Management
Practical Ontology For Enterprise Data ManagementRichard Green
 
How to organize the business layer in software
How to organize the business layer in softwareHow to organize the business layer in software
How to organize the business layer in softwareArnaud LEMAIRE
 
UX in the city Coping with Complexity
UX in the city   Coping with ComplexityUX in the city   Coping with Complexity
UX in the city Coping with ComplexityMemi Beltrame
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaTomer Gabel
 
Asp.net Training at NCrypted Learning Center
Asp.net Training at NCrypted Learning CenterAsp.net Training at NCrypted Learning Center
Asp.net Training at NCrypted Learning CenterNCrypted Learning Center
 
The Power of Composition
The Power of CompositionThe Power of Composition
The Power of CompositionScott Wlaschin
 
Getting the best value out of your unit tests
Getting the best value out of your unit testsGetting the best value out of your unit tests
Getting the best value out of your unit testsRobert Baillie
 
Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...
Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...
Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...Tom Hofte
 
Sap abap part1
Sap abap part1Sap abap part1
Sap abap part1sailesh107
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_conceptAmit Gupta
 

Ähnlich wie Functional Patterns in Domain Modeling (20)

Domain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approachDomain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approach
 
Functional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modelingFunctional and Event Driven - another approach to domain modeling
Functional and Event Driven - another approach to domain modeling
 
Architectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsArchitectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain Models
 
Modelling a complex domain with Domain-Driven Design
Modelling a complex domain with Domain-Driven DesignModelling a complex domain with Domain-Driven Design
Modelling a complex domain with Domain-Driven Design
 
Everything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus scriptEverything you ever wanted to know about lotus script
Everything you ever wanted to know about lotus script
 
The Data Architect Manifesto
The Data Architect ManifestoThe Data Architect Manifesto
The Data Architect Manifesto
 
Starring sakila my sql university 2009
Starring sakila my sql university 2009Starring sakila my sql university 2009
Starring sakila my sql university 2009
 
Practical Ontology For Enterprise Data Management
Practical Ontology For Enterprise Data ManagementPractical Ontology For Enterprise Data Management
Practical Ontology For Enterprise Data Management
 
How to organize the business layer in software
How to organize the business layer in softwareHow to organize the business layer in software
How to organize the business layer in software
 
UX in the city Coping with Complexity
UX in the city   Coping with ComplexityUX in the city   Coping with Complexity
UX in the city Coping with Complexity
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in Scala
 
Asp.net Training at NCrypted Learning Center
Asp.net Training at NCrypted Learning CenterAsp.net Training at NCrypted Learning Center
Asp.net Training at NCrypted Learning Center
 
The Power of Composition
The Power of CompositionThe Power of Composition
The Power of Composition
 
Getting the best value out of your unit tests
Getting the best value out of your unit testsGetting the best value out of your unit tests
Getting the best value out of your unit tests
 
Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...
Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...
Mind The Gap - Mapping a domain model to a RESTful API - OReilly SACon 2018, ...
 
SDWest2005Goetsch
SDWest2005GoetschSDWest2005Goetsch
SDWest2005Goetsch
 
Sap abap part1
Sap abap part1Sap abap part1
Sap abap part1
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Think in linq
Think in linqThink in linq
Think in linq
 
implementing oop_concept
 implementing oop_concept implementing oop_concept
implementing oop_concept
 

Mehr von Debasish Ghosh

Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
 
Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsDebasish Ghosh
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingDebasish Ghosh
 
Mining Functional Patterns
Mining Functional PatternsMining Functional Patterns
Mining Functional PatternsDebasish Ghosh
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesDebasish Ghosh
 
Big Data - architectural concerns for the new age
Big Data - architectural concerns for the new ageBig Data - architectural concerns for the new age
Big Data - architectural concerns for the new ageDebasish Ghosh
 
DSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic modelDSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic modelDebasish Ghosh
 
Dependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDebasish Ghosh
 

Mehr von Debasish Ghosh (8)

Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming Applications
 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
 
Mining Functional Patterns
Mining Functional PatternsMining Functional Patterns
Mining Functional Patterns
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
 
Big Data - architectural concerns for the new age
Big Data - architectural concerns for the new ageBig Data - architectural concerns for the new age
Big Data - architectural concerns for the new age
 
DSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic modelDSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic model
 
Dependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake Pattern
 

Último

Revolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM GridRevolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM GridMathew Thomas
 
Unlocking AI: Navigating Open Source vs. Commercial Frontiers
Unlocking AI:Navigating Open Source vs. Commercial FrontiersUnlocking AI:Navigating Open Source vs. Commercial Frontiers
Unlocking AI: Navigating Open Source vs. Commercial FrontiersRaphaël Semeteys
 
Mobile App Development process | Expert Tips
Mobile App Development process | Expert TipsMobile App Development process | Expert Tips
Mobile App Development process | Expert Tipsmichealwillson701
 
User Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller ResumeUser Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller ResumeKaylee Miller
 
Building Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to startBuilding Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to startMaxim Salnikov
 
Enterprise Content Managements Solutions
Enterprise Content Managements SolutionsEnterprise Content Managements Solutions
Enterprise Content Managements SolutionsIQBG inc
 
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...telebusocialmarketin
 
Einstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdfEinstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdfCloudMetic
 
MUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow ModelsMUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow ModelsUniversity of Antwerp
 
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptx
BusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptxBusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptx
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptxAGATSoftware
 
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxCYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxBarakaMuyengi
 
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...jackiepotts6
 
Practical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfPractical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfICS
 
Mobile App Development company Houston
Mobile  App  Development  company HoustonMobile  App  Development  company Houston
Mobile App Development company Houstonjennysmithusa549
 
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...MyFAA
 
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...Splashtop Inc
 
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...Maxim Salnikov
 
MinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young EntrepreneurMinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young EntrepreneurPriyadarshini T
 
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfFlutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfMind IT Systems
 

Último (20)

Revolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM GridRevolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM Grid
 
Unlocking AI: Navigating Open Source vs. Commercial Frontiers
Unlocking AI:Navigating Open Source vs. Commercial FrontiersUnlocking AI:Navigating Open Source vs. Commercial Frontiers
Unlocking AI: Navigating Open Source vs. Commercial Frontiers
 
Mobile App Development process | Expert Tips
Mobile App Development process | Expert TipsMobile App Development process | Expert Tips
Mobile App Development process | Expert Tips
 
User Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller ResumeUser Experience Designer | Kaylee Miller Resume
User Experience Designer | Kaylee Miller Resume
 
Building Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to startBuilding Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to start
 
Enterprise Content Managements Solutions
Enterprise Content Managements SolutionsEnterprise Content Managements Solutions
Enterprise Content Managements Solutions
 
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
 
Einstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdfEinstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdf
 
MUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow ModelsMUT4SLX: Extensions for Mutation Testing of Stateflow Models
MUT4SLX: Extensions for Mutation Testing of Stateflow Models
 
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptx
BusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptxBusinessGPT  - SECURITY AND GOVERNANCE  FOR GENERATIVE AI.pptx
BusinessGPT - SECURITY AND GOVERNANCE FOR GENERATIVE AI.pptx
 
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxCYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
 
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
 
Practical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfPractical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdf
 
Mobile App Development company Houston
Mobile  App  Development  company HoustonMobile  App  Development  company Houston
Mobile App Development company Houston
 
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
Take Advantage of Mx Tracking Flight Scheduling Solutions to Streamline Your ...
 
20140812 - OBD2 Solution
20140812 - OBD2 Solution20140812 - OBD2 Solution
20140812 - OBD2 Solution
 
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
 
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
 
MinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young EntrepreneurMinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
 
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfFlutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
 

Functional Patterns in Domain Modeling

  • 1. Functional Patterns in Domain Modeling with examples from the Financial Domain @debasishg https://github.com/debasishg http://debasishg.blogspot.com Wednesday, 5 November 14
  • 2. What is a domain model ? A domain model in problem solving and software engineering is a conceptual model of all the topics related to a specific problem. It describes the various entities, their attributes, roles, and relationships, plus the constraints that govern the problem domain. It does not describe the solutions to the problem. Wikipedia (http://en.wikipedia.org/wiki/Domain_model) Wednesday, 5 November 14
  • 3. Rich domain models State Behavior Class • Class models the domain abstraction • Contains both the state and the behavior together • State hidden within private access specifier for fear of being mutated inadvertently • Decision to take - what should go inside a class ? • Decision to take - where do we put behaviors that involve multiple classes ? Often led to bloated service classes State Behavior Wednesday, 5 November 14
  • 4. • Algebraic Data Type (ADT) models the domain abstraction • Contains only the defining state as immutable values • No need to make things “private” since we are talking about immutable values • Nothing but the bare essential definitions go inside an ADT • All behaviors are outside the ADT in modules as functions that define the domain behaviors Lean domain models Immutable State Behavior Immutable State Behavior Algebraic Data Types Functions in modules Wednesday, 5 November 14
  • 5. Rich domain models State Behavior Class • We start with the class design • Make it sufficiently “rich” by putting all related behaviors within the class, used to call them fine grained abstractions • We put larger behaviors in the form of services (aka managers) and used to call them coarse grained abstractions State Behavior Wednesday, 5 November 14
  • 6. Lean domain models Immutable State Behavior • We start with the functions, the behaviors of the domain • We define function algebras using types that don’t have any implementation yet (we will see examples shortly) • Primary focus is on compositionality that enables building larger functions out of smaller ones • Functions reside in modules which also compose • Entities are built with algebraic data types that implement the types we used in defining the functions Immutable State Behavior Algebraic Data Types Functions in modules Wednesday, 5 November 14
  • 8. Domain Model Elements • Entities & Value Objects - modeled with types • Behaviors - modeled with functions • Domain rules - expressed as constraints & validations • Bounded Context - delineates subsystems within the model • Ubiquitous Language Wednesday, 5 November 14
  • 9. .. and some Patterns • Domain object lifecycle patterns Aggregates - encapsulate object references Factories - abstract object creation & management Repositories - manage object persistence & queries Wednesday, 5 November 14
  • 10. .. some more Patterns • Refactoring patterns Making implicit concepts explicit Intention revealing interfaces Side-effect free functions Declarative design Specification for validation Wednesday, 5 November 14
  • 11. The Functional Lens .. Wednesday, 5 November 14
  • 12. Why Functional ? • Ability to reason about your code - virtues of being pure & referentially transparent • Increased modularity - clean separation of state and behavior • Immutable data structures • Concurrency Wednesday, 5 November 14
  • 13. Problem Domain Wednesday, 5 November 14
  • 14. Bank Account Trade Customer ... ... ... Problem Domain ... entities Wednesday, 5 November 14
  • 15. place order Problem Domain Bank Account Trade Customer ... ... ... do trade process execution ... entities behaviors Wednesday, 5 November 14
  • 16. place order Problem Domain Bank Account Trade Customer ... ... ... do trade process execution ... market regulations tax laws brokerage commission rates ... entities behaviors laws Wednesday, 5 November 14
  • 17. place order Problem Domain Bank Account Trade Customer ... ... ... do trade process execution ... market regulations tax laws brokerage commission rates ... entities behaviors laws Wednesday, 5 November 14
  • 18. place order Problem Domain Solution Domain behaviors • Functions do trade process execution ... • On Types • Constraints Wednesday, 5 November 14
  • 19. place order Problem Domain Solution Domain behaviors • Functions do trade process execution ... • On Types • Constraints Algebra • Morphisms • Sets • Laws Wednesday, 5 November 14
  • 20. place order Problem Domain Solution Domain behaviors • Functions do trade process execution ... • On Types • Constraints Algebra • Morphisms • Sets • Laws Compose for larger abstractions Wednesday, 5 November 14
  • 21. A Monoid An algebraic structure having • an identity element • a binary associative operation trait Monoid[A] { def zero: A def op(l: A, r: => A): A } object MonoidLaws { def associative[A: Equal: Monoid] (a1: A, a2: A, a3: A): Boolean = //.. def rightIdentity[A: Equal: Monoid] (a: A) = //.. def leftIdentity[A: Equal: Monoid] (a: A) = //.. } Wednesday, 5 November 14
  • 22. Monoid Laws An algebraic structure havingsa • an identity element • a binary associative operation trait Monoid[A] { def zero: A def op(l: A, r: => A): A } object MonoidLaws { def associative[A: Equal: Monoid] (a1: A, a2: A, a3: A): Boolean = //.. def rightIdentity[A: Equal: Monoid] (a: A) = //.. def leftIdentity[A: Equal: Monoid] (a: A) = //.. } satisfies op(x, zero) == x and op(zero, x) == x satisfies op(op(x, y), z) == op(x, op(y, z)) Wednesday, 5 November 14
  • 23. .. and we talk about domain algebra, where the domain entities are implemented with sets of types and domain behaviors are functions that map a type to one or more types. And domain rules are the laws which define the constraints of the business .. Wednesday, 5 November 14
  • 24. Pattern #1: Functional Modeling encourages Algebraic API Design which leads to organic evolution of domain models Wednesday, 5 November 14
  • 25. Client places order - flexible format 1 Wednesday, 5 November 14
  • 26. Client places order - flexible format 1 2 Transform to internal domain model entity and place for execution Wednesday, 5 November 14
  • 27. Client places order - flexible format 1 2 Transform to internal domain model entity and place for execution Trade & Allocate to client accounts 3 Wednesday, 5 November 14
  • 28. def clientOrders: ClientOrderSheet => List[Order] def execute: Market => Account => Order => List[Execution] def allocate: List[Account] => Execution => List[Trade] Wednesday, 5 November 14
  • 29. Types out of thin air No implementation till now def clientOrders: ClientOrderSheet => List[Order] def execute: Market => Account => Order => List[Execution] def allocate: List[Account] => Execution => List[Trade] Wednesday, 5 November 14
  • 30. Types out of thin air No implementation till now def clientOrders: ClientOrderSheet => List[Order] def execute: Market => Account => Order => List[Execution] def allocate: List[Account] => Execution => List[Trade] Just some types & operations on those types + some laws governing those operations Wednesday, 5 November 14
  • 31. Types out of thin air No implementation till now def clientOrders: ClientOrderSheet => List[Order] Algebra of the API def execute: Market => Account => Order => List[Execution] def allocate: List[Account] => Execution => List[Trade] Just some types & operations on those types + some laws governing those operations Wednesday, 5 November 14
  • 32. Algebraic Design • The algebra is the binding contract of the API • Implementation is NOT part of the algebra • An algebra can have multiple interpreters (aka implementations) • The core principle of functional programming is to decouple the algebra from the interpreter Wednesday, 5 November 14
  • 33. let’s mine some patterns .. def clientOrders: ClientOrderSheet => List[Order] def execute: Market => Account => Order => List[Execution] def allocate: List[Account] => Execution => List[Trade] Wednesday, 5 November 14
  • 34. let’s mine some patterns .. def clientOrders: ClientOrderSheet => List[Order] def execute(m: Market, broker: Account): Order => List[Execution] def allocate(accounts: List[Account]): Execution => List[Trade] Wednesday, 5 November 14
  • 35. let’s mine some patterns .. def clientOrders: ClientOrderSheet => List[Order] def execute(m: Market, broker: Account): Order => List[Execution] def allocate(accounts: List[Account]): Execution => List[Trade] Wednesday, 5 November 14
  • 36. let’s mine some patterns .. def clientOrders: ClientOrderSheet => List[Order] def execute(m: Market, broker: Account): Order => List[Execution] def allocate(accounts: List[Account]): Execution => List[Trade] Wednesday, 5 November 14
  • 37. let’s mine some patterns .. def clientOrders: ClientOrderSheet => List[Order] def execute(m: Market, broker: Account): Order => List[Execution] def allocate(accounts: List[Account]): Execution => List[Trade] Wednesday, 5 November 14
  • 38. let’s mine some patterns .. def clientOrders: ClientOrderSheet => List[Order] def execute(m: Market, broker: Account): Order => List[Execution] def allocate(accounts: List[Account]): Execution => List[Trade] Wednesday, 5 November 14
  • 39. let’s mine some patterns .. def clientOrders: ClientOrderSheet => List[Order] def execute(m: Market, broker: Account): Order => List[Execution] def allocate(accounts: List[Account]): Execution => List[Trade] Function Composition with Effects Wednesday, 5 November 14
  • 40. let’s mine some def clientOrders: ClientOrderSheet => List[Order] def execute(m: Market, broker: Account): Order => List[Execution] def allocate(accounts: List[Account]): Execution => List[Trade] It’s a Kleisli ! patterns .. Wednesday, 5 November 14
  • 41. let’s mine some patterns .. def clientOrders: Kleisli[List, ClientOrderSheet, Order] def execute(m: Market, b: Account): Kleisli[List, Order, Execution] def allocate(acts: List[Account]): Kleisli[List, Execution, Trade] Follow the types Wednesday, 5 November 14
  • 42. let’s mine some patterns .. def tradeGeneration( market: Market, broker: Account, clientAccounts: List[Account]) = { clientOrders andThen execute(market, broker) andThen allocate(clientAccounts) } Implementation follows the specification Wednesday, 5 November 14
  • 43. def tradeGeneration( market: Market, broker: Account, clientAccounts: List[Account]) = { clientOrders andThen execute(market, broker) andThen allocate(clientAccounts) } Implementation follows the specification and we get the Ubiquitous Language for free :-) let’s mine some patterns .. Wednesday, 5 November 14
  • 44. Nouns first ? Really ? Wednesday, 5 November 14
  • 45. Just as the doctor ordered .. ✓Making implicit concepts explicit ✓Intention revealing interfaces ✓Side-effect free functions ✓Declarative design Wednesday, 5 November 14
  • 46. Just as the doctor ordered .. ✓types as the Making implicit functions concepts & explicit patterns for on Claim: With these ✓glue we get all based binding Intention generic revealing abstractions free using function composition interfaces ✓Side-effect free functions ✓Declarative design Wednesday, 5 November 14
  • 47. Pattern #2: DDD patterns like Factories & Specification are part of the normal idioms of functional programming Wednesday, 5 November 14
  • 48. /** * allocates an execution to a List of client accounts * generates a List of trades */ def allocate(accounts: List[Account]): Kleisli[List, Execution, Trade] = kleisli { execution => accounts.map { account => makeTrade(account, execution.instrument, genRef(), execution.market, execution.unitPrice, execution.quantity / accounts.size ) } } Wednesday, 5 November 14
  • 49. /** * allocates an execution to a List of client accounts * generates a List of trades */ def allocate(accounts: List[Account]): Kleisli[List, Execution, Trade] = kleisli { execution => accounts.map { account => makeTrade(account, execution.instrument, genRef(), execution.market, execution.unitPrice, execution.quantity / accounts.size ) } } Wednesday, 5 November 14
  • 50. /** * allocates an execution to a List of client accounts * generates a List of trades */ def allocate(accounts: List[Account]): Kleisli[List, Execution, Trade] = kleisli { execution => accounts.map { account => makeTrade(account, execution.instrument, genRef(), execution.market, execution.unitPrice, execution.quantity / accounts.size ) } } Makes a Trade out of the parameters passed What about validations ? How do we handle failures ? Wednesday, 5 November 14
  • 51. case class Trade (account: Account, instrument: Instrument, refNo: String, market: Market, unitPrice: BigDecimal, quantity: BigDecimal, tradeDate: Date = today, valueDate: Option[Date] = None, taxFees: Option[List[(TaxFeeId, BigDecimal)]] = None, netAmount: Option[BigDecimal] = None ) Wednesday, 5 November 14
  • 52. must be > 0 case class Trade (account: Account, instrument: Instrument, refNo: String, market: Market, unitPrice: BigDecimal, quantity: BigDecimal, tradeDate: Date = today, valueDate: Option[Date] = None, taxFees: Option[List[(TaxFeeId, BigDecimal)]] = None, netAmount: Option[BigDecimal] = None ) must be > trade date Wednesday, 5 November 14
  • 53. Monads .. Wednesday, 5 November 14
  • 54. monadic validation pattern def makeTrade(account: Account, instrument: Instrument, refNo: String, market: Market, unitPrice: BigDecimal, quantity: BigDecimal, td: Date = today, vd: Option[Date] = None): ValidationStatus[Trade] = { val trd = Trade(account, instrument, refNo, market, unitPrice, quantity, td, vd) val s = for { _ <- validQuantity _ <- validValueDate t <- validUnitPrice } yield t s(trd) } Wednesday, 5 November 14
  • 55. monadic validation pattern def makeTrade(account: Account, instrument: Instrument, refNo: String, market: Market, unitPrice: BigDecimal, quantity: BigDecimal, td: Date = today, vd: Option[Date] = None): ValidationStatus[Trade] = { val trd = Trade(account, instrument, refNo, market, unitPrice, quantity, td, vd) val s = for { _ <- validQuantity _ <- validValueDate t <- validUnitPrice } yield t s(trd) } (monad comprehension) Wednesday, 5 November 14
  • 56. monadic validation pattern Smart Constructor : The def makeTrade(account: Account, instrument: Instrument, refNo: String, market: Market, unitPrice: BigDecimal, quantity: BigDecimal, td: Date = today, vd: Option[Date] = None): ValidationStatus[Trade] = { val trd = Trade(account, instrument, refNo, Factory Pattern (Chapter 6) market, unitPrice, quantity, td, vd) val s = for { _ <- validQuantity _ <- validValueDate t <- validUnitPrice } yield t s(trd) } The Specification Pattern (Chapter 9) Wednesday, 5 November 14
  • 57. let’s mine some more patterns (with types) .. disjunction type (a sum type ValidationStatus[S] = /[String, S] type ReaderTStatus[A, S] = ReaderT[ValidationStatus, A, S] object ReaderTStatus extends KleisliInstances with KleisliFunctions { def apply[A, S](f: A => ValidationStatus[S]): ReaderTStatus[A, S] = kleisli(f) } type) : either a valid object or a failure message monad transformer Wednesday, 5 November 14
  • 58. monadic validation pattern .. def validQuantity = ReaderTStatus[Trade, Trade] { trade => if (trade.quantity < 0) left(s"Quantity needs to be > 0 for $trade") else right(trade) } def validUnitPrice = ReaderTStatus[Trade, Trade] { trade => if (trade.unitPrice < 0) left(s"Unit Price needs to be > 0 for $trade") else right(trade) } def validValueDate = ReaderTStatus[Trade, Trade] { trade => trade.valueDate.map(vd => if (trade.tradeDate after vd) left(s"Trade Date ${trade.tradeDate} must be before value date $vd") else right(trade) ).getOrElse(right(trade)) } Wednesday, 5 November 14
  • 59. With Functional Programming • we implement all specific patterns in terms of generic abstractions • all these generic abstractions are based on function composition • and encourage immutability & referential transparency Wednesday, 5 November 14
  • 60. Pattern #3: Functional Modeling encourages parametricity, i.e. abstract logic from specific types to generic ones Wednesday, 5 November 14
  • 61. case class Trade( refNo: String, instrument: Instrument, tradeDate: Date, valueDate: Date, principal: Money, taxes: List[Tax], ... ) Wednesday, 5 November 14
  • 62. case class Trade( refNo: String, instrument: Instrument, tradeDate: Date, valueDate: Date, principal: Money, taxes: List[Tax], ... ) case class Money(amount: BigDecimal, ccy: Currency) { def +(m: Money) = { sealed trait Currency case object USD extends Currency case object AUD extends Currency case object SGD extends Currency case object INR extends Currency require(m.ccy == ccy) Money(amount + m.amount, ccy) } def >(m: Money) = { require(m.ccy == ccy) if (amount > m.amount) this else m } } Wednesday, 5 November 14
  • 63. case class Trade( refNo: String, instrument: Instrument, tradeDate: Date, valueDate: Date, principal: Money, taxes: List[Tax], ... ) def netValue: Trade => Money = //.. Given a list of trades, find the total net valuation of all trades in base currency Wednesday, 5 November 14
  • 64. def inBaseCcy: Money => Money = //.. def valueTradesInBaseCcy(ts: List[Trade]) = { ts.foldLeft(Money(0, baseCcy)) { (acc, e) => acc + inBaseCcy(netValue(e)) } } Wednesday, 5 November 14
  • 65. case class Transaction(id: String, value: Money) Given a list of transactions for a customer, find the highest valued transaction Wednesday, 5 November 14
  • 66. case class Transaction(id: String, value: Money) def highestValueTxn(txns: List[Transaction]) = { txns.foldLeft(Money(0, baseCcy)) { (acc, e) => Given a list of transactions for a customer, find the highest valued transaction acc > e.value } } Wednesday, 5 November 14
  • 67. fold on the collection def valueTradesInBaseCcy(ts: List[Trade]) = { ts.foldLeft(Money(0, baseCcy)) { (acc, e) => acc + inBaseCcy(netValue(e)) } } def highestValueTxn(txns: List[Transaction]) = { txns.foldLeft(Money(0, baseCcy)) { (acc, e) => acc > e.value } } Wednesday, 5 November 14
  • 68. zero on Money associative binary operation on Money def valueTradesInBaseCcy(ts: List[Trade]) = { ts.foldLeft(Money(0, baseCcy)) { (acc, e) => acc + inBaseCcy(netValue(e)) } } def highestValueTxn(txns: List[Transaction]) = { txns.foldLeft(Money(0, baseCcy)) { (acc, e) => acc > e.value } } Wednesday, 5 November 14
  • 69. Instead of the specific collection type (List), we can abstract over the type constructor using the more general Foldable def valueTradesInBaseCcy(ts: List[Trade]) = { ts.foldLeft(Money(0, baseCcy)) { (acc, e) => acc + inBaseCcy(netValue(e)) } } def highestValueTxn(txns: List[Transaction]) = { txns.foldLeft(Money(0, baseCcy)) { (acc, e) => acc > e.value } } Wednesday, 5 November 14
  • 70. look ma .. Monoid for Money ! def valueTradesInBaseCcy(ts: List[Trade]) = { ts.foldLeft(Money(0, baseCcy)) { (acc, e) => acc + inBaseCcy(netValue(e)) } } def highestValueTxn(txns: List[Transaction]) = { txns.foldLeft(Money(0, baseCcy)) { (acc, e) => acc > e.value } } Wednesday, 5 November 14
  • 71. fold the collection on a monoid Foldable abstracts over the type constructor Monoid abstracts over the operation Wednesday, 5 November 14
  • 72. def mapReduce[F[_], A, B](as: F[A])(f: A => B) (implicit fd: Foldable[F], m: Monoid[B]) = fd.foldMap(as)(f) Wednesday, 5 November 14
  • 73. def mapReduce[F[_], A, B](as: F[A])(f: A => B) (implicit fd: Foldable[F], m: Monoid[B]) = fd.foldMap(as)(f) def valueTradesInBaseCcy(ts: List[Trade]) = mapReduce(ts)(netValue andThen inBaseCcy) def highestValueTxn(txns: List[Transaction]) = mapReduce(txns)(_.value) Wednesday, 5 November 14
  • 74. trait Foldable[F[_]] { def foldl[A, B](as: F[A], z: B, f: (B, A) => B): B def foldMap[A, B](as: F[A], f: A => B)(implicit m: Monoid[B]): B = foldl(as, m.zero, (b: B, a: A) => m.add(b, f(a))) } implicit val listFoldable = new Foldable[List] { def foldl[A, B](as: List[A], z: B, f: (B, A) => B) = as.foldLeft(z)(f) } Wednesday, 5 November 14
  • 75. implicit def MoneyMonoid(implicit c: Currency) = new Monoid[Money] { def zero: Money = Money(BigDecimal(0), c) def append(m1: Money, m2: => Money) = m1 + m2 } implicit def MaxMoneyMonoid(implicit c: Currency) = new Monoid[Money] { def zero: Money = Money(BigDecimal(0), c) def append(m1: Money, m2: => Money) = m1 > m2 } Wednesday, 5 November 14
  • 76. def mapReduce[F[_], A, B](as: F[A])(f: A => B) (implicit fd: Foldable[F], m: Monoid[B]) = fd.foldMap(as)(f) def valueTradesInBaseCcy(ts: List[Trade]) = mapReduce(ts)(netValue andThen inBaseCcy) def highestValueTxn(txns: List[Transaction]) = mapReduce(txns)(_.value) This last pattern is inspired from Runar’s response on this SoF thread http://stackoverflow.com/questions/4765532/what-does-abstract-over-mean Wednesday, 5 November 14
  • 77. Takeaways .. • Moves the algebra from domain specific abstractions to more generic ones • The program space in the mapReduce function is shrunk - so scope of error is reduced • Increases the parametricity of our program - mapReduce is now parametric in type parameters A and B (for all A and B) Wednesday, 5 November 14
  • 78. When using functional modeling, always try to express domain specific abstractions and behaviors in terms of more generic, lawful abstractions. Doing this you make your functions more generic, more usable in a broader context and yet simpler to comprehend. This is the concept of parametricity and is one of the Wednesday, 5 November 14
  • 79. Use code “mlghosh2” for a 50% discount Wednesday, 5 November 14
  • 80. Image acknowledgements • www.valuewalk.com • http://bienabee.com • http://www.ownta.com • http://ebay.in • http://www.clker.com • http://homepages.inf.ed.ac.uk/wadler/ • http://en.wikipedia.org Wednesday, 5 November 14
  • 81. Thank You! Wednesday, 5 November 14