SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
Monoids
Piyush Mishra
Software Consultant
Knoldus Software LLP
Topics Covered
What is Monoid
Formal definition of a Monoid
Define a String Monoid
Define a Int Monoid
Define a List Monoid
Fold lists with Monoids
What is Monoid
Monoids are certain common patterns followed by the
algebras of various data types of a programming language .
Integers with addition. We know that (a+b)+c == a+(b+c) and 0+n == n+0
== n
same with multiplication: (a*b)*c == a*(b*c) and 1*n == n*1 == n
Strings with concatenation. a+(b+c)==(a+b)+c; ""+s==s and s+"" == s,
etc.
Lists with concatenation, like List(1,2)+List(3,4) == List(1,2,3,4)
Sets with their union, like Set(1,2,3)+Set(2,4) == Set(1,2,3,4).
This + binary operation is the common pattern.
Formal definition of a monoid
Given a type A, a binary operation Op:(A,A) => A, and an
instance Zero: A, with the properties that will be specified
below, the triple (A, Op, Zero) is called a monoid. Here are
the properties:
Neutral or identity element : Zero `Op` a == a `Op` Zero == a
Associativity: (a `Op` b) `Op` c == a `Op` (b `Op` c)
We can express this with a Scala trait:
trait Monoid[A] {
def op(a1: A, a2: A): A
def zero: A
}
Define a String monoid
trait BaseMonoid[A] {
def op(a: A, b: A): A
def zero: A
}
class StringMonoid extends BaseMonoid[String] {
def op(a: String, b: String) = (a.trim + " " + b.trim).trim
def zero = ""
}
Here we a operation (op) in which we adding two string with
space delimiter.
Define a Int monoid
trait BaseMonoid[A] {
def op(a: A, b: A): A
def zero: A
}
class IntegerMonoid extends BaseMonoid[Int] {
def op(a: Int, b: Int) = a + b
def zero = 0
}
Here we a operation (op) in which we sum two two integer
Define a List monoid
trait BaseMonoid[A] {
def op(a: A, b: A): A
def zero: A
}
class ListMonoid[A] extends BaseMonoid[List[A]] {
def op(a: List[A], b: List[A]): List[A] = a ++ b
def zero = Nil
}
Here we a operation (op) in which we adding two two Lists
Folding a list with a monoid
def foldRight(z: A)(f: (A, A) => A): A
def foldLeft(z: A)(f: (A, A) => A): A
val words = List("hello", "world", "Whats Up")
scala> val s = words.foldRight(stringMonoid.zero)
(stringMonoid.op)
s: String = "hello world Whats Up"
scala> val t = words.foldLeft(stringMonoid.zero)
(stringMonoid.op)
t: String = "hello world Whats Up"
Function which folds a list with a
monoid
def concatenate[A](as: List[A], m: Monoid[A]): A
def concatenate[A](as: List[A], m: BaseMonoid[A]): A =
as.foldRight(m.zero)(m.op)
Operation using different monoids
instance
def foldMap[A,B](as: List[A], m: Monoid[B])(f: A => B): B
def foldMap[A, B](as: List[A], m: Monoid[B])(f: A => B): B =
as.foldLeft(m.zero)((b, a) => m.op(b, f(a)))
Manipulate a json using monoid
val json = """{
"first": "John",
"last": "Doe",
"credit_card": 5105105105105100,
"ssn": "123-45-6789",
"salary": 70000,
"registered": true }"""
class JsonMonoid extends Monoid[String] {
val CREDIT_CARD_REGEX = "bd{13,16}b"
val SSN_REGEX = "b[0-9]{3}-[0-9]{2}-[0-9]{4}b"
val BLOCK_TEXT = "*********"
def identity = ""
def op(a1: String, a2: String) = a1 + a2.replaceAll(CREDIT_CARD_REGEX,
BLOCK_TEXT).replaceAll(SSN_REGEX, BLOCK_TEXT) + ","
}
val monoid = new JsonMonoid
val result = json.split(',').foldLeft(monoid.identity)(monoid.op)
Thanks

Weitere Àhnliche Inhalte

Was ist angesagt?

Selection in Evolutionary Algorithm
Selection in Evolutionary AlgorithmSelection in Evolutionary Algorithm
Selection in Evolutionary Algorithm
Riyad Parvez
 

Was ist angesagt? (20)

Selection in Evolutionary Algorithm
Selection in Evolutionary AlgorithmSelection in Evolutionary Algorithm
Selection in Evolutionary Algorithm
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Recurrence relations
Recurrence relationsRecurrence relations
Recurrence relations
 
04 brute force
04 brute force04 brute force
04 brute force
 
Application Of Graph Data Structure
Application Of Graph Data StructureApplication Of Graph Data Structure
Application Of Graph Data Structure
 
The n Queen Problem
The n Queen ProblemThe n Queen Problem
The n Queen Problem
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithm
 
Sorting algorithm
Sorting algorithmSorting algorithm
Sorting algorithm
 
FYBSC IT Web Programming Unit II Html Page Layout & Navigation
FYBSC IT Web Programming Unit II Html Page Layout & NavigationFYBSC IT Web Programming Unit II Html Page Layout & Navigation
FYBSC IT Web Programming Unit II Html Page Layout & Navigation
 
Group By, Having Clause and Order By clause
Group By, Having Clause and Order By clause Group By, Having Clause and Order By clause
Group By, Having Clause and Order By clause
 
Graphs in Data Structure
 Graphs in Data Structure Graphs in Data Structure
Graphs in Data Structure
 
Tsp is NP-Complete
Tsp is NP-CompleteTsp is NP-Complete
Tsp is NP-Complete
 
Content provider in_android
Content provider in_androidContent provider in_android
Content provider in_android
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Characterization and Comparison
Characterization and ComparisonCharacterization and Comparison
Characterization and Comparison
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 

Ähnlich wie Monoids

Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
Vasil Remeniuk
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
Mohd Arif
 

Ähnlich wie Monoids (20)

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
 
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
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 
Array
ArrayArray
Array
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 
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)
 
Making Logic Monad
Making Logic MonadMaking Logic Monad
Making Logic Monad
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
 
Mining Functional Patterns
Mining Functional PatternsMining Functional Patterns
Mining Functional Patterns
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
 

Mehr von Knoldus Inc.

Mehr von Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

KĂŒrzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

KĂŒrzlich hochgeladen (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Monoids

  • 2. Topics Covered What is Monoid Formal definition of a Monoid Define a String Monoid Define a Int Monoid Define a List Monoid Fold lists with Monoids
  • 3. What is Monoid Monoids are certain common patterns followed by the algebras of various data types of a programming language . Integers with addition. We know that (a+b)+c == a+(b+c) and 0+n == n+0 == n same with multiplication: (a*b)*c == a*(b*c) and 1*n == n*1 == n Strings with concatenation. a+(b+c)==(a+b)+c; ""+s==s and s+"" == s, etc. Lists with concatenation, like List(1,2)+List(3,4) == List(1,2,3,4) Sets with their union, like Set(1,2,3)+Set(2,4) == Set(1,2,3,4). This + binary operation is the common pattern.
  • 4. Formal definition of a monoid Given a type A, a binary operation Op:(A,A) => A, and an instance Zero: A, with the properties that will be specified below, the triple (A, Op, Zero) is called a monoid. Here are the properties: Neutral or identity element : Zero `Op` a == a `Op` Zero == a Associativity: (a `Op` b) `Op` c == a `Op` (b `Op` c) We can express this with a Scala trait: trait Monoid[A] { def op(a1: A, a2: A): A def zero: A }
  • 5. Define a String monoid trait BaseMonoid[A] { def op(a: A, b: A): A def zero: A } class StringMonoid extends BaseMonoid[String] { def op(a: String, b: String) = (a.trim + " " + b.trim).trim def zero = "" } Here we a operation (op) in which we adding two string with space delimiter.
  • 6. Define a Int monoid trait BaseMonoid[A] { def op(a: A, b: A): A def zero: A } class IntegerMonoid extends BaseMonoid[Int] { def op(a: Int, b: Int) = a + b def zero = 0 } Here we a operation (op) in which we sum two two integer
  • 7. Define a List monoid trait BaseMonoid[A] { def op(a: A, b: A): A def zero: A } class ListMonoid[A] extends BaseMonoid[List[A]] { def op(a: List[A], b: List[A]): List[A] = a ++ b def zero = Nil } Here we a operation (op) in which we adding two two Lists
  • 8. Folding a list with a monoid def foldRight(z: A)(f: (A, A) => A): A def foldLeft(z: A)(f: (A, A) => A): A val words = List("hello", "world", "Whats Up") scala> val s = words.foldRight(stringMonoid.zero) (stringMonoid.op) s: String = "hello world Whats Up" scala> val t = words.foldLeft(stringMonoid.zero) (stringMonoid.op) t: String = "hello world Whats Up"
  • 9. Function which folds a list with a monoid def concatenate[A](as: List[A], m: Monoid[A]): A def concatenate[A](as: List[A], m: BaseMonoid[A]): A = as.foldRight(m.zero)(m.op)
  • 10. Operation using different monoids instance def foldMap[A,B](as: List[A], m: Monoid[B])(f: A => B): B def foldMap[A, B](as: List[A], m: Monoid[B])(f: A => B): B = as.foldLeft(m.zero)((b, a) => m.op(b, f(a)))
  • 11. Manipulate a json using monoid val json = """{ "first": "John", "last": "Doe", "credit_card": 5105105105105100, "ssn": "123-45-6789", "salary": 70000, "registered": true }""" class JsonMonoid extends Monoid[String] { val CREDIT_CARD_REGEX = "bd{13,16}b" val SSN_REGEX = "b[0-9]{3}-[0-9]{2}-[0-9]{4}b" val BLOCK_TEXT = "*********" def identity = "" def op(a1: String, a2: String) = a1 + a2.replaceAll(CREDIT_CARD_REGEX, BLOCK_TEXT).replaceAll(SSN_REGEX, BLOCK_TEXT) + "," } val monoid = new JsonMonoid val result = json.split(',').foldLeft(monoid.identity)(monoid.op)