SlideShare a Scribd company logo
1 of 12
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 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))
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 =
foldRight(as, ma.unit, (a,b) => ma.combine(a,b))
def foldRight[A,B](as: List[A], b: B, f: (A, B) => B): B = as match
case Nil => b
case Cons(a,rest) => f(a,foldRight(rest,b,f))
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))
Same as the previous slide,
except that here we define
fold in terms of foldRight.
@philip_schwarz
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

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

Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceAlexey Raga
 
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 ...Philip Schwarz
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collectionsMyeongin Woo
 
FP in scalaで鍛える関数型脳
FP in scalaで鍛える関数型脳FP in scalaで鍛える関数型脳
FP in scalaで鍛える関数型脳Yuri Inoue
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
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 ScalaPhilip Schwarz
 
Agda であそぼ
Agda であそぼAgda であそぼ
Agda であそぼerutuf13
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
Each team works on assigned sorting algorithms and will give demonstr.pdf
Each team works on assigned sorting algorithms and will give demonstr.pdfEach team works on assigned sorting algorithms and will give demonstr.pdf
Each team works on assigned sorting algorithms and will give demonstr.pdfomarionmatzmcwill497
 
Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2Hang Zhao
 
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)Eric Torreborre
 
学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2Opt Technologies
 
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 learnpavan373
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 

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

Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
 
Lambda calculus
Lambda calculusLambda calculus
Lambda calculus
 
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 ...
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
FP in scalaで鍛える関数型脳
FP in scalaで鍛える関数型脳FP in scalaで鍛える関数型脳
FP in scalaで鍛える関数型脳
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
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
 
Agda であそぼ
Agda であそぼAgda であそぼ
Agda であそぼ
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
04-Sets-Relations-A.pdf
04-Sets-Relations-A.pdf04-Sets-Relations-A.pdf
04-Sets-Relations-A.pdf
 
Each team works on assigned sorting algorithms and will give demonstr.pdf
Each team works on assigned sorting algorithms and will give demonstr.pdfEach team works on assigned sorting algorithms and will give demonstr.pdf
Each team works on assigned sorting algorithms and will give demonstr.pdf
 
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
 
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)
 
学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2
 
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
 
Monoids
MonoidsMonoids
Monoids
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
ScalaBlitz
ScalaBlitzScalaBlitz
ScalaBlitz
 
Scala Parallel Collections
Scala Parallel CollectionsScala Parallel Collections
Scala Parallel Collections
 

More from Philip Schwarz

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 seriesPhilip Schwarz
 
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 seriesPhilip Schwarz
 
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 seriesPhilip Schwarz
 
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 seriesPhilip Schwarz
 
Scala Left Fold Parallelisation - Three Approaches
Scala Left Fold Parallelisation- Three ApproachesScala Left Fold Parallelisation- Three Approaches
Scala Left Fold Parallelisation - Three ApproachesPhilip Schwarz
 
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 ProgramsPhilip Schwarz
 
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 ViewsPhilip Schwarz
 
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 ScalaPhilip Schwarz
 
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 ScalaPhilip Schwarz
 
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 ScalaPhilip Schwarz
 
N-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsN-Queens Combinatorial Puzzle meets Cats
N-Queens Combinatorial Puzzle meets CatsPhilip Schwarz
 
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...Philip Schwarz
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...Philip Schwarz
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...Philip Schwarz
 
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...Philip Schwarz
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...Philip Schwarz
 
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 axiomsPhilip Schwarz
 
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...Philip Schwarz
 
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 (...Philip Schwarz
 
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 correctionsPhilip Schwarz
 

More from Philip Schwarz (20)

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...
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
 
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...
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
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
 

Recently uploaded

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

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 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. 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 = foldRight(as, ma.unit, (a,b) => ma.combine(a,b)) def foldRight[A,B](as: List[A], b: B, f: (A, B) => B): B = as match case Nil => b case Cons(a,rest) => f(a,foldRight(rest,b,f)) 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)) Same as the previous slide, except that here we define fold in terms of foldRight. @philip_schwarz
  • 8. 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)
  • 9. 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) 𝒅𝒂𝒕𝒂 𝑴𝒂𝒚𝒃𝒆 𝛼 = 𝑵𝒐𝒕𝒉𝒊𝒏𝒈 | 𝑱𝒖𝒔𝒕 𝛼
  • 10. 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))
  • 11. 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)))
  • 12. That’s all. I hope you found it useful. @philip_schwarz