SlideShare uma empresa Scribd logo
1 de 19
Baixar para ler offline
Truth, Deduction,
Computation
Lecture 4
Monoids
Vlad Patryshev
SCU
2013
See common pattern?
●

2+3==5; 0+n==n+0==n

●

6*7==42; 1*n==n*1==n

●

max(10, 100) == 100; max(Int.MinValue, x) == x

●

"ab"+"cd"=="abcd"; ""+"ef"=="ef"; "gh"+""=="gh"

●

List(1,2)+List(3,4)==List(1,2,3,4); Nil+List(5,6)==List
(5,6); List(7,8)+Nil==List(7,8)

●

Set(1,2,3)+Set(2,4)==Set(1,2,3,4); Set.Empty+Set(5,6)
==Set(5,6)
You see Monoids!
●

2+3==5; 0+n==n+0==n

●

6*7==42; 1*n==n*1==n

●

max(10, 100) == 100; max(Int.MinValue, x) == x

●

"ab"+"cd"=="abcd"; ""+"ef"=="ef"; "gh"+""=="gh"

●

List(1,2)+List(3,4)==List(1,2,3,4); Nil+List(5,6)==List
(5,6); List(7,8)++Nil==List(7,8)

●

Set(1,2,3)+Set(2,4)==Set(1,2,3,4); Set.Empty+Set(5,6)
==Set(5,6)
Monoid Rules
1)

a Op b = c

2) Zero Op a = a Op Zero = a
signatures:
Op: (T, T) => T
Zero: () => T // or rather just T

but wait, there's more!
Monoid Rules - associativity
(a Op b) Op c == a Op (b Op c)
Not everything is associative
5-(3-2) != (5-3)-2
avg(10, avg(30, 50)) != avg(avg(10, 30), 50)
Magma - like monoid, but no associativity and no unit
●

Tuples: (a, (b, c)) is not the same as ((a,b), c)

●

Binary trees:
Monoid Rules - associativity
(a1 Op (a2 Op (a3 Op (a4...))))
aka fold
(Zero /: a) (x Op y)
Can regroup and run in parallel: thanks to associativity!

This is what empowers Map/Reduce
Mappings between Monoids
f: A → B
f(ZeroA) = ZeroB
f(x OpA y) = f(x) OpB f(y)
e.g.
●
●
●
●
●
●

log(1)=0; log(a*b)=log(a)+log(b)
twice(n)=2*n; twice(0)=0, twice(n+m)=twice(n)+twice(m)
length("")=0; length(s1+s2)=length(s1)+length(s2)
sum(Nil)=0; sum(list1+list2)=sum(list1)+sum(list2)
prod(Nil)=1; prod(list1+list2)=prod(list1)*prod(list2)
maxOf(Nil)=Int.MinValue; maxOf(list1+list2)=max(maxOf
(list1)),maxOf(list2))
Free Monoid
any type

a monoid

take any function, f: A → B
this is equivalent to specifying...
f': List[A] → B
where
f'(Nil) = ZeroB
f'(list1 + list2) = f'(list1) OpB f'(list2)
List[A] is a Free Monoid on A
Free Monoid - example
Suppose we have...
object WeekDay extends Enumeration {
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
and a function
WeekDay=>Int = (Mon->1, Tue->1, Wed->1, Thu->1, Fri->1,
Sat->0, Sun->0)
If we have a monoid (Int, 0, +), we can automatically extend this
mapping to List[WeekDay]->Int
which counts the number of working days.
Reduce
reduce: List[A] → A
with properties:

●
●

reduce(Nil) = ZeroA
reduce(list1+list2) = reduce(list1) OpA reduce(list2)

(This defines an algebra over the functor List[_].)
This is exactly what we did on the previous page, reduce.
That's almost it
Monoids are simple, are not they?
Let's throw in more properties...
Commutative Monoids
a Op b == b Op a
e.g.

●
●

2+3==3+2
max(2.72, 3.14) == max(3.14, 2.72)

but not these:

●
●

"hello" + "world" != "world" + "hello"
List(1,2,3)+List(4,5,6) != List(4,5,6)+List(1,2,3)
Commutative Monoids
How can we create one?
e.g.
"abracadabra" -> "aaaaabbcdrr"
Order does not matter; numbers matter.
Free commutative monoid on A: a collection of possibly duplicates, order
does not matter.
It is called Bag[A]
Commutative Monoids
Bag[A]
<script language=”javascript”>
var bag =
{
"partridges in a pear tree": 1,
"turtle doves": 2,
"french hens": 3,
"calling birds": 4,
"golden rings": 5
//etc
}
</script>
Commutative Monoids
How about sets?!
Commutative Monoids...
How about sets?!
x Op x == x

x is idempotent

Set('a','b','c') + Set('b','c','d') = Set('a','b','c','d')
Commutative Monoids...
How about sets?!
x Op x == x : x is idempotent
Set('a','b','c') + Set('b','c','d') = Set('a','b','c','d')

another example

●
●

max(x, x) = x
min(x, x) = x
Big Picture

The Whole Picture

(source: Alexander Bunkenburg, "The Boom Hierarchy")
Questions?

http://vpatryshev.blogspot.com/2009/06/why-monoids.html (with Java examples)
http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/

Mais conteúdo relacionado

Mais procurados (14)

Ch13 20
Ch13 20Ch13 20
Ch13 20
 
Integral table
Integral tableIntegral table
Integral table
 
Ch03 12
Ch03 12Ch03 12
Ch03 12
 
Tugas matematika menemukan konsep persamaan kuadrat
Tugas matematika menemukan konsep persamaan kuadratTugas matematika menemukan konsep persamaan kuadrat
Tugas matematika menemukan konsep persamaan kuadrat
 
Legendre's eqaution
Legendre's eqautionLegendre's eqaution
Legendre's eqaution
 
MS2 POwer Rules
MS2 POwer RulesMS2 POwer Rules
MS2 POwer Rules
 
Integral table
Integral tableIntegral table
Integral table
 
Etude Des Proprietes Physicochimiques Et Caracterisation Dune Argile Locale
Etude Des Proprietes Physicochimiques Et Caracterisation Dune Argile LocaleEtude Des Proprietes Physicochimiques Et Caracterisation Dune Argile Locale
Etude Des Proprietes Physicochimiques Et Caracterisation Dune Argile Locale
 
Integrales
Integrales Integrales
Integrales
 
Intro To Agda
Intro To AgdaIntro To Agda
Intro To Agda
 
Zadaci iz matisha
Zadaci iz matisha Zadaci iz matisha
Zadaci iz matisha
 
Divisor de 7
Divisor de 7Divisor de 7
Divisor de 7
 
Bsc maths derivative_formula
Bsc maths derivative_formulaBsc maths derivative_formula
Bsc maths derivative_formula
 
Jordan's solution
Jordan's solutionJordan's solution
Jordan's solution
 

Destaque (7)

Gao
GaoGao
Gao
 
Ka rin carol wedemeyer
Ka rin   carol wedemeyerKa rin   carol wedemeyer
Ka rin carol wedemeyer
 
Truth, deduction, computation; lecture 3
Truth, deduction, computation;  lecture 3Truth, deduction, computation;  lecture 3
Truth, deduction, computation; lecture 3
 
Truth, deduction, computation lecture i (last one)
Truth, deduction, computation   lecture i (last one)Truth, deduction, computation   lecture i (last one)
Truth, deduction, computation lecture i (last one)
 
Bill & june vaughn
Bill & june vaughnBill & june vaughn
Bill & june vaughn
 
Bains
BainsBains
Bains
 
Josi's ceramics thingy
Josi's ceramics thingyJosi's ceramics thingy
Josi's ceramics thingy
 

Semelhante a Truth, deduction, computation; lecture 4

Semelhante a Truth, deduction, computation; lecture 4 (20)

Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 
Number theory lecture (part 1)
Number theory lecture (part 1)Number theory lecture (part 1)
Number theory lecture (part 1)
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Hw5sols
Hw5solsHw5sols
Hw5sols
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Mi ordenador, de mayor, quiere ser cuántico (curso acelerado de simulación ...
Mi ordenador, de mayor, quiere ser cuántico (curso acelerado de simulación ...Mi ordenador, de mayor, quiere ser cuántico (curso acelerado de simulación ...
Mi ordenador, de mayor, quiere ser cuántico (curso acelerado de simulación ...
 
Brief intro to clojure
Brief intro to clojureBrief intro to clojure
Brief intro to clojure
 
Grokking Monads in Scala
Grokking Monads in ScalaGrokking Monads in Scala
Grokking Monads in Scala
 
Python overview
Python overviewPython overview
Python overview
 
Top school in delhi ncr
Top school in delhi ncrTop school in delhi ncr
Top school in delhi ncr
 
L10 sorting-searching
L10 sorting-searchingL10 sorting-searching
L10 sorting-searching
 
Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889
 
Lp presentations fnctions
Lp presentations fnctionsLp presentations fnctions
Lp presentations fnctions
 
Functions ppt Dr Frost Maths Mixed questions
Functions ppt Dr Frost Maths Mixed questionsFunctions ppt Dr Frost Maths Mixed questions
Functions ppt Dr Frost Maths Mixed questions
 
Send + More = Money – Let’s mash 2 monads to solve a simple CSP
Send + More = Money – Let’s mash 2 monads to solve a simple CSPSend + More = Money – Let’s mash 2 monads to solve a simple CSP
Send + More = Money – Let’s mash 2 monads to solve a simple CSP
 
FUNCTIONS L.1.pdf
FUNCTIONS L.1.pdfFUNCTIONS L.1.pdf
FUNCTIONS L.1.pdf
 
C programs
C programsC programs
C programs
 
Real number system full
Real  number  system fullReal  number  system full
Real number system full
 

Mais de Vlad Patryshev

Mais de Vlad Patryshev (20)

Formal methods 8 - category theory (last one)
Formal methods   8 - category theory (last one)Formal methods   8 - category theory (last one)
Formal methods 8 - category theory (last one)
 
Formal methods 6 - elements of algebra
Formal methods   6 - elements of algebraFormal methods   6 - elements of algebra
Formal methods 6 - elements of algebra
 
Formal methods 5 - Pi calculus
Formal methods   5 - Pi calculusFormal methods   5 - Pi calculus
Formal methods 5 - Pi calculus
 
Formal methods 4 - Z notation
Formal methods   4 - Z notationFormal methods   4 - Z notation
Formal methods 4 - Z notation
 
Formal methods 3 - languages and machines
Formal methods   3 - languages and machinesFormal methods   3 - languages and machines
Formal methods 3 - languages and machines
 
Formal methods 2 - languages and machines
Formal methods   2 - languages and machinesFormal methods   2 - languages and machines
Formal methods 2 - languages and machines
 
Formal methods 1 - introduction
Formal methods   1 - introductionFormal methods   1 - introduction
Formal methods 1 - introduction
 
Formal methods 7 - category theory
Formal methods   7 - category theoryFormal methods   7 - category theory
Formal methods 7 - category theory
 
Truth, deduction, computation lecture h
Truth, deduction, computation   lecture hTruth, deduction, computation   lecture h
Truth, deduction, computation lecture h
 
Truth, deduction, computation lecture g
Truth, deduction, computation   lecture gTruth, deduction, computation   lecture g
Truth, deduction, computation lecture g
 
Truth, deduction, computation lecture f
Truth, deduction, computation   lecture fTruth, deduction, computation   lecture f
Truth, deduction, computation lecture f
 
Truth, deduction, computation lecture e
Truth, deduction, computation   lecture eTruth, deduction, computation   lecture e
Truth, deduction, computation lecture e
 
Truth, deduction, computation lecture d
Truth, deduction, computation   lecture dTruth, deduction, computation   lecture d
Truth, deduction, computation lecture d
 
Truth, deduction, computation lecture c
Truth, deduction, computation   lecture cTruth, deduction, computation   lecture c
Truth, deduction, computation lecture c
 
Truth, deduction, computation lecture b
Truth, deduction, computation   lecture bTruth, deduction, computation   lecture b
Truth, deduction, computation lecture b
 
Truth, deduction, computation lecture a
Truth, deduction, computation   lecture aTruth, deduction, computation   lecture a
Truth, deduction, computation lecture a
 
Truth, deduction, computation lecture 9
Truth, deduction, computation   lecture 9Truth, deduction, computation   lecture 9
Truth, deduction, computation lecture 9
 
Truth, deduction, computation lecture 8
Truth, deduction, computation   lecture 8Truth, deduction, computation   lecture 8
Truth, deduction, computation lecture 8
 
Truth, deduction, computation lecture 7
Truth, deduction, computation   lecture 7Truth, deduction, computation   lecture 7
Truth, deduction, computation lecture 7
 
Truth, deduction, computation lecture 6
Truth, deduction, computation   lecture 6Truth, deduction, computation   lecture 6
Truth, deduction, computation lecture 6
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

Truth, deduction, computation; lecture 4

  • 2. See common pattern? ● 2+3==5; 0+n==n+0==n ● 6*7==42; 1*n==n*1==n ● max(10, 100) == 100; max(Int.MinValue, x) == x ● "ab"+"cd"=="abcd"; ""+"ef"=="ef"; "gh"+""=="gh" ● List(1,2)+List(3,4)==List(1,2,3,4); Nil+List(5,6)==List (5,6); List(7,8)+Nil==List(7,8) ● Set(1,2,3)+Set(2,4)==Set(1,2,3,4); Set.Empty+Set(5,6) ==Set(5,6)
  • 3. You see Monoids! ● 2+3==5; 0+n==n+0==n ● 6*7==42; 1*n==n*1==n ● max(10, 100) == 100; max(Int.MinValue, x) == x ● "ab"+"cd"=="abcd"; ""+"ef"=="ef"; "gh"+""=="gh" ● List(1,2)+List(3,4)==List(1,2,3,4); Nil+List(5,6)==List (5,6); List(7,8)++Nil==List(7,8) ● Set(1,2,3)+Set(2,4)==Set(1,2,3,4); Set.Empty+Set(5,6) ==Set(5,6)
  • 4. Monoid Rules 1) a Op b = c 2) Zero Op a = a Op Zero = a signatures: Op: (T, T) => T Zero: () => T // or rather just T but wait, there's more!
  • 5. Monoid Rules - associativity (a Op b) Op c == a Op (b Op c) Not everything is associative 5-(3-2) != (5-3)-2 avg(10, avg(30, 50)) != avg(avg(10, 30), 50) Magma - like monoid, but no associativity and no unit ● Tuples: (a, (b, c)) is not the same as ((a,b), c) ● Binary trees:
  • 6. Monoid Rules - associativity (a1 Op (a2 Op (a3 Op (a4...)))) aka fold (Zero /: a) (x Op y) Can regroup and run in parallel: thanks to associativity! This is what empowers Map/Reduce
  • 7. Mappings between Monoids f: A → B f(ZeroA) = ZeroB f(x OpA y) = f(x) OpB f(y) e.g. ● ● ● ● ● ● log(1)=0; log(a*b)=log(a)+log(b) twice(n)=2*n; twice(0)=0, twice(n+m)=twice(n)+twice(m) length("")=0; length(s1+s2)=length(s1)+length(s2) sum(Nil)=0; sum(list1+list2)=sum(list1)+sum(list2) prod(Nil)=1; prod(list1+list2)=prod(list1)*prod(list2) maxOf(Nil)=Int.MinValue; maxOf(list1+list2)=max(maxOf (list1)),maxOf(list2))
  • 8. Free Monoid any type a monoid take any function, f: A → B this is equivalent to specifying... f': List[A] → B where f'(Nil) = ZeroB f'(list1 + list2) = f'(list1) OpB f'(list2) List[A] is a Free Monoid on A
  • 9. Free Monoid - example Suppose we have... object WeekDay extends Enumeration { val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value } and a function WeekDay=>Int = (Mon->1, Tue->1, Wed->1, Thu->1, Fri->1, Sat->0, Sun->0) If we have a monoid (Int, 0, +), we can automatically extend this mapping to List[WeekDay]->Int which counts the number of working days.
  • 10. Reduce reduce: List[A] → A with properties: ● ● reduce(Nil) = ZeroA reduce(list1+list2) = reduce(list1) OpA reduce(list2) (This defines an algebra over the functor List[_].) This is exactly what we did on the previous page, reduce.
  • 11. That's almost it Monoids are simple, are not they? Let's throw in more properties...
  • 12. Commutative Monoids a Op b == b Op a e.g. ● ● 2+3==3+2 max(2.72, 3.14) == max(3.14, 2.72) but not these: ● ● "hello" + "world" != "world" + "hello" List(1,2,3)+List(4,5,6) != List(4,5,6)+List(1,2,3)
  • 13. Commutative Monoids How can we create one? e.g. "abracadabra" -> "aaaaabbcdrr" Order does not matter; numbers matter. Free commutative monoid on A: a collection of possibly duplicates, order does not matter. It is called Bag[A]
  • 14. Commutative Monoids Bag[A] <script language=”javascript”> var bag = { "partridges in a pear tree": 1, "turtle doves": 2, "french hens": 3, "calling birds": 4, "golden rings": 5 //etc } </script>
  • 16. Commutative Monoids... How about sets?! x Op x == x x is idempotent Set('a','b','c') + Set('b','c','d') = Set('a','b','c','d')
  • 17. Commutative Monoids... How about sets?! x Op x == x : x is idempotent Set('a','b','c') + Set('b','c','d') = Set('a','b','c','d') another example ● ● max(x, x) = x min(x, x) = x
  • 18. Big Picture The Whole Picture (source: Alexander Bunkenburg, "The Boom Hierarchy")
  • 19. Questions? http://vpatryshev.blogspot.com/2009/06/why-monoids.html (with Java examples) http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/