SlideShare a Scribd company logo
1 of 11
Download to read offline
@philip_schwarz
slides by https://www.slideshare.net/pjschwarz
Nat, List and Option Monoids
from scratch
Combining and Folding
an example
enum Nat:
case Zero
case Succ(n: Nat)
𝐝𝐚𝐭𝐚 𝑵𝒂𝒕 = 𝒁𝒆𝒓𝒐 | 𝑺𝒖𝒄𝒄 𝑵𝒂𝒕
+ ∷ 𝑵𝒂𝒕 → 𝑵𝒂𝒕 → 𝑵𝒂𝒕
𝑚 + 𝒁𝒆𝒓𝒐 = 𝑚
𝑚 + 𝑺𝒖𝒄𝒄 𝑛 = 𝑺𝒖𝒄𝒄 𝑚 + 𝑛
(×) ∷ 𝑵𝒂𝒕 → 𝑵𝒂𝒕 → 𝑵𝒂𝒕
𝑚 × 𝒁𝒆𝒓𝒐 = 𝒁𝒆𝒓𝒐
𝑚 × 𝑺𝒖𝒄𝒄 𝑛 = 𝑚 × 𝑛 + 𝑚 extension (m: Nat)
def +(n: Nat): Nat = n match
case Zero => m
case Succ(n) => Succ(m + n)
def *(n: Nat): Nat = n match
case Zero => Zero
case Succ(n) => m * n + m
assert( zero + one == one )
assert( one + zero == one )
assert( one + two == three )
assert( one + two + three == six )
val zero = Zero
val one = Succ(zero)
val two = Succ(one)
val three = Succ(two)
val four = Succ(three)
val five = Succ(four)
val six = Succ(five)
assert( two * one == two )
assert( one * two == two )
assert( two * three == six )
assert( one * two * three == six )
trait Semigroup[A]:
def combine(x: A, y: A): A
object Semigroup:
extension [A](lhs: A)(using m: Semigroup[A])
def ⨁(rhs: A): A = m.combine(lhs,rhs)
given Monoid[Nat] with
def unit: Nat = Zero
def combine(x: Nat, y: Nat): Nat = x + y
trait Monoid[A] extends Semigroup[A]:
def unit: A
assert( summon[Monoid[Nat]].combine(two,three) == five )
assert( (two ⨁ three) == five )
assert( (one ⨁ two ⨁ three) == six )
val oneTwo = Cons(one,Cons(two,Nil))
val threeFour = Cons(three,Cons(four,Nil))
assert(append(oneTwo,threeFour) == Cons(one,Cons(two,Cons(three,Cons(four,Nil)))))
assert(oneTwo ++ threeFour == Cons(one,Cons(two,Cons(three,Cons(four,Nil)))))
enum List[+A]:
case Cons(head: A, tail: List[A])
case Nil
𝒅𝒂𝒕𝒂 𝑳𝒊𝒔𝒕 𝛼 = 𝑵𝒊𝒍 | 𝑪𝒐𝒏𝒔 𝛼 (𝑳𝒊𝒔𝒕 𝛼)
𝑪𝒐𝒏𝒔 1 (𝑪𝒐𝒏𝒔 2 (𝑪𝒐𝒏𝒔 3 𝑵𝒊𝒍 ))
object List:
def apply[A](as: A*): List[A] = as match
case Seq() => Nil
case _ => Cons(as.head, List(as.tail*))
def append[A](lhs: List[A], rhs: List[A]): List[A] = lhs match
case Nil => rhs
case Cons(a, rest) => Cons(a,append(rest,rhs))
extension [A](lhs: List[A])
def ++(rhs: List[A]): List[A] = append(lhs,rhs)
assert(List(one,two,three) == Cons(one,Cons(two,Cons(three,Nil))))
assert(List(one,two) ++ List(three, four) ++ Nil == List(one,two,three,four))
given ListMonoid[A]: Monoid[List[A]] with
def unit: List[A] = Nil
def combine(lhs: List[A], rhs: List[A]): List[A] = lhs ++ rhs
assert(summon[Monoid[List[Nat]]].combine(List(one,two),List(three, four)) == List(one,two,three,four))
assert((List(one,two) ⨁ List(three, four)) == List(one,two,three,four))
object List:
def apply[A](as: A*): List[A] = as match
case Seq() => Nil
case _ => Cons(as.head, List(as.tail*))
def append[A](lhs: List[A], rhs: List[A]): List[A] = lhs match
case Nil => rhs
case Cons(a, rest) => Cons(a,append(rest,rhs))
extension [A](lhs: List[A])
def ++(rhs: List[A]): List[A] = append(lhs,rhs)
object List:
def apply[A](as: A*): List[A] = as match
case Seq() => Nil
case _ => Cons(as.head, List(as.tail*))
def nil[A]: List[A] = Nil
def append[A](lhs: List[A], rhs: List[A]): List[A] = lhs match
case Nil => rhs
case Cons(a, rest) => Cons(a,append(rest,rhs))
extension [A](lhs: List[A])
def ++(rhs: List[A]): List[A] = append(lhs,rhs)
def fold[A](as: List[A])(using ma: Monoid[A]): A = as match
case Nil => ma.unit
case Cons(a,rest) => ma.combine(a,fold(rest))
assert(fold(List(one,two,three,four)) == one + two + three + four)
assert(fold(nil[Nat]) == zero)
assert(fold(List(List(one,two),Nil,List(three, four),List(five,six)))
== List(one,two,three,four,five,six))
val natMultMonoid = new Monoid[Nat]:
def unit: Nat = Succ(Zero)
def combine(x: Nat, y: Nat): Nat = x * y
assert(fold(List(one,two,three,four))(using natMultMonoid) == one * two * three * four)
assert(fold(nil[Nat])(using natMultMonoid) == one)
given OptionMonoid[A:Semigroup]: Monoid[Option[A]] with
def unit: Option[A] = None
def combine(ox: Option[A], oy: Option[A]): Option[A] = (ox,oy) match
case (None,_) => oy
case (_,None) => ox
case (Some(x),Some(y)) => Some(x ⨁ y)
enum Option[+A]:
case None
case Some(value:A)
object Option:
def none[A]: Option[A] = None
def some[A](a:A): Option[A] = Some(a)
assert((some(two) ⨁ None) == Some(two))
assert((none[Nat] ⨁ Some(two)) == Some(two))
assert((some(two) ⨁ Some(three)) == Some(five))
assert((none[Nat] ⨁ None) == None)
assert(summon[Monoid[Option[Nat]]].combine(Some(two),Some(three)) == Some(five))
assert(summon[Monoid[Option[Nat]]].combine(Some(two),None) == Some(two))
assert(summon[Monoid[Option[Nat]]].combine(none[Nat],Some(two)) == Some(two))
assert(summon[Monoid[Option[Nat]]].combine(none[Nat],None) == None)
𝒅𝒂𝒕𝒂 𝑴𝒂𝒚𝒃𝒆 𝛼 = 𝑵𝒐𝒕𝒉𝒊𝒏𝒈 | 𝑱𝒖𝒔𝒕 𝛼
assert(fold(List(Some(two),None,Some(three))) == Some(five))
assert(fold(nil[Option[Nat]]) == None)
assert((List(Some(one),None,Some(two)) ++ List(Some(three),None,Some(four)))
== List(Some(one),None,Some(two),Some(three),None,Some(four)))
assert(summon[Monoid[List[Option[Nat]]]].combine(List(Some(one),None,Some(two)),List(Some(three),None,Some(four)))
== List(Some(one),None,Some(two),Some(three),None,Some(four)))
assert((List(Some(one),None,Some(two)) ⨁ List(Some(three),None,Some(four)))
== List(Some(one),None,Some(two),Some(three),None,Some(four)))
assert(fold(List(Some(one),None,Some(two)) ⨁ List(Some(three),None,Some(four)))
== Some(one + two + three + four))
assert(
fold(
fold(
List(List(Some(one), None, Some(two)),
List(Some(three), None, Some(four)),
List(Some(five), None, Some(six)))
)
)
== Some(one + two + three + four + five + six))
assert((some(List(one,two)) ⨁ None ⨁ Some(List(three,four)))
== Some(List(one,two,three,four)))
That’s all.
I hope you found it useful.
@philip_schwarz

More Related Content

What's hot

What's hot (20)

Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...
 
Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018
 
The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
 
Lazy java
Lazy javaLazy java
Lazy java
 
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
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
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Regular Expressions in Java
Regular Expressions in JavaRegular Expressions in Java
Regular Expressions in Java
 
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
 
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorldFunctional Programming 101 with Scala and ZIO @FunctionalWorld
Functional Programming 101 with Scala and ZIO @FunctionalWorld
 

Similar to Nat, List and Option Monoids - from scratch - Combining and Folding - an example

Ozma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyOzma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrency
BeScala
 
Agda であそぼ
Agda であそぼAgda であそぼ
Agda であそぼ
erutuf13
 

Similar to Nat, List and Option Monoids - from scratch - Combining and Folding - an example (20)

Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
[Expert Fridays] Александр Чичигин - Как перестать бояться и полюбить COQ
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
 
Ozma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyOzma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrency
 
Agda であそぼ
Agda であそぼAgda であそぼ
Agda であそぼ
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaFolding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
 
Lambda calculus
Lambda calculusLambda calculus
Lambda calculus
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
mat lab introduction and basics to learn
mat lab introduction and basics to learnmat lab introduction and basics to learn
mat lab introduction and basics to learn
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
 
Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2
 
Truth, deduction, computation lecture g
Truth, deduction, computation   lecture gTruth, deduction, computation   lecture g
Truth, deduction, computation lecture g
 
A/B Testing for Game Design
A/B Testing for Game DesignA/B Testing for Game Design
A/B Testing for Game Design
 
04-Sets-Relations-A.pdf
04-Sets-Relations-A.pdf04-Sets-Relations-A.pdf
04-Sets-Relations-A.pdf
 
ScalaBlitz
ScalaBlitzScalaBlitz
ScalaBlitz
 

More from Philip Schwarz

N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
Philip Schwarz
 

More from Philip Schwarz (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Folding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a seriesFolding Cheat Sheet #3 - third in a series
Folding Cheat Sheet #3 - third in a series
 
Folding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a seriesFolding Cheat Sheet #2 - second in a series
Folding Cheat Sheet #2 - second in a series
 
Folding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a seriesFolding Cheat Sheet #1 - first in a series
Folding Cheat Sheet #1 - first in a series
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three Approaches
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
 
Fusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with ViewsFusing Transformations of Strict Scala Collections with Views
Fusing Transformations of Strict Scala Collections with Views
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
 
A sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in ScalaA sighting of traverseFilter and foldMap in Practical FP in Scala
A sighting of traverseFilter and foldMap in Practical FP in Scala
 
A sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in ScalaA sighting of sequence function in Practical FP in Scala
A sighting of sequence function in Practical FP in Scala
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets Cats
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
 
Jordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axiomsJordan Peterson - The pursuit of meaning and related ethical axioms
Jordan Peterson - The pursuit of meaning and related ethical axioms
 
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
Defining filter using (a) recursion (b) folding (c) folding with S, B and I c...
 
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...Defining filter using (a) recursion (b) folding with S, B and I combinators (...
Defining filter using (a) recursion (b) folding with S, B and I combinators (...
 
The Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor correctionsThe Sieve of Eratosthenes - Part 1 - with minor corrections
The Sieve of Eratosthenes - Part 1 - with minor corrections
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1b
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 

Recently uploaded

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Recently uploaded (20)

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 

Nat, List and Option Monoids - from scratch - Combining and Folding - an example

  • 1. @philip_schwarz slides by https://www.slideshare.net/pjschwarz Nat, List and Option Monoids from scratch Combining and Folding an example
  • 2. enum Nat: case Zero case Succ(n: Nat) 𝐝𝐚𝐭𝐚 𝑵𝒂𝒕 = 𝒁𝒆𝒓𝒐 | 𝑺𝒖𝒄𝒄 𝑵𝒂𝒕 + ∷ 𝑵𝒂𝒕 → 𝑵𝒂𝒕 → 𝑵𝒂𝒕 𝑚 + 𝒁𝒆𝒓𝒐 = 𝑚 𝑚 + 𝑺𝒖𝒄𝒄 𝑛 = 𝑺𝒖𝒄𝒄 𝑚 + 𝑛 (×) ∷ 𝑵𝒂𝒕 → 𝑵𝒂𝒕 → 𝑵𝒂𝒕 𝑚 × 𝒁𝒆𝒓𝒐 = 𝒁𝒆𝒓𝒐 𝑚 × 𝑺𝒖𝒄𝒄 𝑛 = 𝑚 × 𝑛 + 𝑚 extension (m: Nat) def +(n: Nat): Nat = n match case Zero => m case Succ(n) => Succ(m + n) def *(n: Nat): Nat = n match case Zero => Zero case Succ(n) => m * n + m assert( zero + one == one ) assert( one + zero == one ) assert( one + two == three ) assert( one + two + three == six ) val zero = Zero val one = Succ(zero) val two = Succ(one) val three = Succ(two) val four = Succ(three) val five = Succ(four) val six = Succ(five) assert( two * one == two ) assert( one * two == two ) assert( two * three == six ) assert( one * two * three == six )
  • 3. trait Semigroup[A]: def combine(x: A, y: A): A object Semigroup: extension [A](lhs: A)(using m: Semigroup[A]) def ⨁(rhs: A): A = m.combine(lhs,rhs) given Monoid[Nat] with def unit: Nat = Zero def combine(x: Nat, y: Nat): Nat = x + y trait Monoid[A] extends Semigroup[A]: def unit: A assert( summon[Monoid[Nat]].combine(two,three) == five ) assert( (two ⨁ three) == five ) assert( (one ⨁ two ⨁ three) == six )
  • 4. val oneTwo = Cons(one,Cons(two,Nil)) val threeFour = Cons(three,Cons(four,Nil)) assert(append(oneTwo,threeFour) == Cons(one,Cons(two,Cons(three,Cons(four,Nil))))) assert(oneTwo ++ threeFour == Cons(one,Cons(two,Cons(three,Cons(four,Nil))))) enum List[+A]: case Cons(head: A, tail: List[A]) case Nil 𝒅𝒂𝒕𝒂 𝑳𝒊𝒔𝒕 𝛼 = 𝑵𝒊𝒍 | 𝑪𝒐𝒏𝒔 𝛼 (𝑳𝒊𝒔𝒕 𝛼) 𝑪𝒐𝒏𝒔 1 (𝑪𝒐𝒏𝒔 2 (𝑪𝒐𝒏𝒔 3 𝑵𝒊𝒍 )) object List: def apply[A](as: A*): List[A] = as match case Seq() => Nil case _ => Cons(as.head, List(as.tail*)) def append[A](lhs: List[A], rhs: List[A]): List[A] = lhs match case Nil => rhs case Cons(a, rest) => Cons(a,append(rest,rhs)) extension [A](lhs: List[A]) def ++(rhs: List[A]): List[A] = append(lhs,rhs)
  • 5. assert(List(one,two,three) == Cons(one,Cons(two,Cons(three,Nil)))) assert(List(one,two) ++ List(three, four) ++ Nil == List(one,two,three,four)) given ListMonoid[A]: Monoid[List[A]] with def unit: List[A] = Nil def combine(lhs: List[A], rhs: List[A]): List[A] = lhs ++ rhs assert(summon[Monoid[List[Nat]]].combine(List(one,two),List(three, four)) == List(one,two,three,four)) assert((List(one,two) ⨁ List(three, four)) == List(one,two,three,four)) object List: def apply[A](as: A*): List[A] = as match case Seq() => Nil case _ => Cons(as.head, List(as.tail*)) def append[A](lhs: List[A], rhs: List[A]): List[A] = lhs match case Nil => rhs case Cons(a, rest) => Cons(a,append(rest,rhs)) extension [A](lhs: List[A]) def ++(rhs: List[A]): List[A] = append(lhs,rhs)
  • 6. object List: def apply[A](as: A*): List[A] = as match case Seq() => Nil case _ => Cons(as.head, List(as.tail*)) def nil[A]: List[A] = Nil def append[A](lhs: List[A], rhs: List[A]): List[A] = lhs match case Nil => rhs case Cons(a, rest) => Cons(a,append(rest,rhs)) extension [A](lhs: List[A]) def ++(rhs: List[A]): List[A] = append(lhs,rhs) def fold[A](as: List[A])(using ma: Monoid[A]): A = as match case Nil => ma.unit case Cons(a,rest) => ma.combine(a,fold(rest)) assert(fold(List(one,two,three,four)) == one + two + three + four) assert(fold(nil[Nat]) == zero) assert(fold(List(List(one,two),Nil,List(three, four),List(five,six))) == List(one,two,three,four,five,six))
  • 7. val natMultMonoid = new Monoid[Nat]: def unit: Nat = Succ(Zero) def combine(x: Nat, y: Nat): Nat = x * y assert(fold(List(one,two,three,four))(using natMultMonoid) == one * two * three * four) assert(fold(nil[Nat])(using natMultMonoid) == one)
  • 8. given OptionMonoid[A:Semigroup]: Monoid[Option[A]] with def unit: Option[A] = None def combine(ox: Option[A], oy: Option[A]): Option[A] = (ox,oy) match case (None,_) => oy case (_,None) => ox case (Some(x),Some(y)) => Some(x ⨁ y) enum Option[+A]: case None case Some(value:A) object Option: def none[A]: Option[A] = None def some[A](a:A): Option[A] = Some(a) assert((some(two) ⨁ None) == Some(two)) assert((none[Nat] ⨁ Some(two)) == Some(two)) assert((some(two) ⨁ Some(three)) == Some(five)) assert((none[Nat] ⨁ None) == None) assert(summon[Monoid[Option[Nat]]].combine(Some(two),Some(three)) == Some(five)) assert(summon[Monoid[Option[Nat]]].combine(Some(two),None) == Some(two)) assert(summon[Monoid[Option[Nat]]].combine(none[Nat],Some(two)) == Some(two)) assert(summon[Monoid[Option[Nat]]].combine(none[Nat],None) == None) 𝒅𝒂𝒕𝒂 𝑴𝒂𝒚𝒃𝒆 𝛼 = 𝑵𝒐𝒕𝒉𝒊𝒏𝒈 | 𝑱𝒖𝒔𝒕 𝛼
  • 9. assert(fold(List(Some(two),None,Some(three))) == Some(five)) assert(fold(nil[Option[Nat]]) == None) assert((List(Some(one),None,Some(two)) ++ List(Some(three),None,Some(four))) == List(Some(one),None,Some(two),Some(three),None,Some(four))) assert(summon[Monoid[List[Option[Nat]]]].combine(List(Some(one),None,Some(two)),List(Some(three),None,Some(four))) == List(Some(one),None,Some(two),Some(three),None,Some(four))) assert((List(Some(one),None,Some(two)) ⨁ List(Some(three),None,Some(four))) == List(Some(one),None,Some(two),Some(three),None,Some(four))) assert(fold(List(Some(one),None,Some(two)) ⨁ List(Some(three),None,Some(four))) == Some(one + two + three + four))
  • 10. assert( fold( fold( List(List(Some(one), None, Some(two)), List(Some(three), None, Some(four)), List(Some(five), None, Some(six))) ) ) == Some(one + two + three + four + five + six)) assert((some(List(one,two)) ⨁ None ⨁ Some(List(three,four))) == Some(List(one,two,three,four)))
  • 11. That’s all. I hope you found it useful. @philip_schwarz