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

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 ...Philip Schwarz
Β 
β€˜go-to’ general-purpose sequential collections - from Java To Scala
β€˜go-to’ general-purpose sequential collections -from Java To Scalaβ€˜go-to’ general-purpose sequential collections -from Java To Scala
β€˜go-to’ general-purpose sequential collections - from Java To ScalaPhilip Schwarz
Β 
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...Philip Schwarz
Β 
Kleisli Composition
Kleisli CompositionKleisli Composition
Kleisli CompositionPhilip Schwarz
Β 
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 CatsPhilip Schwarz
Β 
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
Β 
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
Β 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative FunctorPhilip Schwarz
Β 
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 @FunctionalWorldJorge VΓ‘squez
Β 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
Β 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
Β 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022Alexander Ioffe
Β 
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
Β 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
Β 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Philip Schwarz
Β 

What's hot (20)

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 ...
Β 
β€˜go-to’ general-purpose sequential collections - from Java To Scala
β€˜go-to’ general-purpose sequential collections -from Java To Scalaβ€˜go-to’ general-purpose sequential collections -from Java To Scala
β€˜go-to’ general-purpose sequential collections - from Java To Scala
Β 
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...
Β 
Kleisli Composition
Kleisli CompositionKleisli Composition
Kleisli Composition
Β 
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
Β 
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
Β 
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...
Β 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
Β 
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
Β 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
Β 
Lazy java
Lazy javaLazy java
Lazy java
Β 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
Β 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
Β 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022
Β 
Zio in real world
Zio in real worldZio in real world
Zio in real world
Β 
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...
Β 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
Β 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
Β 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1
Β 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside
Β 

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

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 examplePhilip Schwarz
Β 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scalaRaymond Tay
Β 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scalaSiarhiej Siemianchuk
Β 
[Expert Fridays] АлСксандр Π§ΠΈΡ‡ΠΈΠ³ΠΈΠ½ - Как ΠΏΠ΅Ρ€Π΅ΡΡ‚Π°Ρ‚ΡŒ Π±ΠΎΡΡ‚ΡŒΡΡ ΠΈ ΠΏΠΎΠ»ΡŽΠ±ΠΈΡ‚ΡŒ COQ
[Expert Fridays] АлСксандр Π§ΠΈΡ‡ΠΈΠ³ΠΈΠ½ - Как ΠΏΠ΅Ρ€Π΅ΡΡ‚Π°Ρ‚ΡŒ Π±ΠΎΡΡ‚ΡŒΡΡ ΠΈ ΠΏΠΎΠ»ΡŽΠ±ΠΈΡ‚ΡŒ COQ[Expert Fridays] АлСксандр Π§ΠΈΡ‡ΠΈΠ³ΠΈΠ½ - Как ΠΏΠ΅Ρ€Π΅ΡΡ‚Π°Ρ‚ΡŒ Π±ΠΎΡΡ‚ΡŒΡΡ ΠΈ ΠΏΠΎΠ»ΡŽΠ±ΠΈΡ‚ΡŒ COQ
[Expert Fridays] АлСксандр Π§ΠΈΡ‡ΠΈΠ³ΠΈΠ½ - Как ΠΏΠ΅Ρ€Π΅ΡΡ‚Π°Ρ‚ΡŒ Π±ΠΎΡΡ‚ΡŒΡΡ ΠΈ ΠΏΠΎΠ»ΡŽΠ±ΠΈΡ‚ΡŒ COQProvectus
Β 
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
Β 
Ozma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyOzma: Extending Scala with Oz concurrency
Ozma: Extending Scala with Oz concurrencyBeScala
Β 
Agda であそぼ
Agda であそぼAgda であそぼ
Agda であそぼerutuf13
Β 
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
Β 
Lambda calculus
Lambda calculusLambda calculus
Lambda calculusAttila Magyar
Β 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
Β 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala 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
Β 
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
Β 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceAlexey Raga
Β 
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
Β 
Truth, deduction, computation lecture g
Truth, deduction, computation   lecture gTruth, deduction, computation   lecture g
Truth, deduction, computation lecture gVlad Patryshev
Β 
A/B Testing for Game Design
A/B Testing for Game DesignA/B Testing for Game Design
A/B Testing for Game DesignTrieu Nguyen
Β 

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

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
Β 
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
Β 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access PrinciplePhilip Schwarz
Β 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bPhilip Schwarz
Β 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2Philip Schwarz
Β 
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 1Philip 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...
Β 
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
Β 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
Β 
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

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
Β 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
Β 
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
Β 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
Β 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
Β 
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
Β 
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
Β 
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
Β 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
Β 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
Β 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
Β 
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.
Β 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto GonzΓ‘lez Trastoy
Β 
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
Β 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
Β 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
Β 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
Β 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
Β 
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
Β 

Recently uploaded (20)

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
Β 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
Β 
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
Β 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
Β 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
Β 
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...
Β 
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
Β 
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 ...
Β 
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)
Β 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
Β 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
Β 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
Β 
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...
Β 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Β 
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
Β 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Β 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
Β 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Β 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Β 
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
Β 

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