SlideShare une entreprise Scribd logo
1  sur  47
Télécharger pour lire hors ligne
Functional Algebra
    Monoids Applied


       Susan Potter




      Nov 10, 2012
OMG, Algebra? FML.. . .
OMG, Algebra? FML.. . .




     Figure: Chill! Algebra is just a domain specific language
% whoami




      Figure: From OO patterns to FP abstractions
Monoids: What are they?

  An abstraction (laws)
  not a design pattern (forces, context, . . . )


  Algebraic structure . . .
  over a set with a binary operator and an identity element


  Accumulator . . .
  Its sole purpose


  Special case category . . .
  with only one object
Monoids: What are they?

  An abstraction (laws)
  not a design pattern (forces, context, . . . )


  Algebraic structure . . .
  over a set with a binary operator and an identity element


  Accumulator . . .
  Its sole purpose


  Special case category . . .
  with only one object
Monoids: What are they?

  An abstraction (laws)
  not a design pattern (forces, context, . . . )


  Algebraic structure . . .
  over a set with a binary operator and an identity element


  Accumulator . . .
  Its sole purpose


  Special case category . . .
  with only one object
Monoids: What are they?

  An abstraction (laws)
  not a design pattern (forces, context, . . . )


  Algebraic structure . . .
  over a set with a binary operator and an identity element


  Accumulator . . .
  Its sole purpose


  Special case category . . .
  with only one object
Monoids: Typeclasses
           Listing 1: Haskell Monoid Typeclass Definition
1 -- | In Haskell Prelude Data. Monoid
2 class Monoid a where
3   mempty :: a            -- identity
4   mappend :: a -> a -> a -- binary op
5   mconcat :: [a] -> a -- helper

              Listing 2: Scalaz Monoid Trait Definition
1 // Scalaz 7’s Monoid typeclass definition , kinda
2 trait Monoid [A] extends Semigroup [A] { self =>
3   def zero: A                    /* identity */
4   def append(x: A, y: => A): A /* binary op */
5 }
6   // from SemigroupOps [A] ...
7   final def |+|(other: => A): A = A.append(self, other)
Monoids: Typeclasses
           Listing 3: Haskell Monoid Typeclass Definition
1 -- | In Haskell Prelude Data. Monoid
2 class Monoid a where
3   mempty :: a            -- identity
4   mappend :: a -> a -> a -- binary op
5   mconcat :: [a] -> a -- helper

              Listing 4: Scalaz Monoid Trait Definition
1 // Scalaz 7’s Monoid typeclass definition , kinda
2 trait Monoid [A] extends Semigroup [A] { self =>
3   def zero: A                    /* identity */
4   def append(x: A, y: => A): A /* binary op */
5 }
6   // from SemigroupOps [A] ...
7   final def |+|(other: => A): A = A.append(self, other)
Monoids: Typeclasses
           Listing 5: Haskell Monoid Typeclass Definition
1 -- | In Haskell Prelude Data. Monoid
2 class Monoid a where
3   mempty :: a            -- identity
4   mappend :: a -> a -> a -- binary op
5   mconcat :: [a] -> a -- helper

              Listing 6: Scalaz Monoid Trait Definition
1 // Scalaz 7’s Monoid typeclass definition , kinda
2 trait Monoid [A] extends Semigroup [A] { self =>
3   def zero: A                    /* identity */
4   def append(x: A, y: => A): A /* binary op */
5 }
6   // from SemigroupOps [A] ...
7   final def |+|(other: => A): A = A.append(self, other)
Monoids: Typeclasses
           Listing 7: Haskell Monoid Typeclass Definition
1 -- | In Haskell Prelude Data. Monoid
2 class Monoid a where
3   mempty :: a            -- identity
4   mappend :: a -> a -> a -- binary op
5   mconcat :: [a] -> a -- helper

              Listing 8: Scalaz Monoid Trait Definition
1 // Scalaz 7’s Monoid typeclass definition , kinda
2 trait Monoid [A] extends Semigroup [A] { self =>
3   def zero: A                    /* identity */
4   def append(x: A, y: => A): A /* binary op */
5 }
6   // from SemigroupOps [A] ...
7   final def |+|(other: => A): A = A.append(self, other)
Monoids: Laws

  Closure: ∀a, b ∈ S : ab ∈ S
  for all a and b in set S, the result of a and b given to the binary operator
  is also in set S.


  Associativity: ∀a, b, c ∈ S : (ab)c = a(bc)
  for all a, b, and c in set S, either binary operator can be evaluated first
  to produce same result.


  Identity: ∃e ∈ S : ∀a ∈ S : ea = a = ae
  there exists an e in set S such that for all a in set S ea evaluates to a
  and is equal to ae
Monoids: Laws

  Closure: ∀a, b ∈ S : ab ∈ S
  for all a and b in set S, the result of a and b given to the binary operator
  is also in set S.


  Associativity: ∀a, b, c ∈ S : (ab)c = a(bc)
  for all a, b, and c in set S, either binary operator can be evaluated first
  to produce same result.


  Identity: ∃e ∈ S : ∀a ∈ S : ea = a = ae
  there exists an e in set S such that for all a in set S ea evaluates to a
  and is equal to ae
Monoids: Laws

  Closure: ∀a, b ∈ S : ab ∈ S
  for all a and b in set S, the result of a and b given to the binary operator
  is also in set S.


  Associativity: ∀a, b, c ∈ S : (ab)c = a(bc)
  for all a, b, and c in set S, either binary operator can be evaluated first
  to produce same result.


  Identity: ∃e ∈ S : ∀a ∈ S : ea = a = ae
  there exists an e in set S such that for all a in set S ea evaluates to a
  and is equal to ae
Monoids: Properties (Haskell)
 1   -- property based tests for monoid "laws"
 2   -- does not compile yet; must specify type a
 3   module Tests where
 4   import Test. QuickCheck ( quickCheck )
 5
 6   -- closure law verified by type system
 7
 8   propMonoidAssoc :: Monoid a => a -> a -> a -> Bool
 9   propMonoidAssoc x y z =
10     mappend ( mappend x y) z == mappend x ( mappend y z)
11
12   propMonoidIdent :: Monoid a => a -> Bool
13   propMonoidIdent x =
14     mappend mempty x == x && mappend x mempty == x
Monoids: Simple "Natural" Examples
                            Listing 9: Haskell
1   --      OP      ID      List
2   foldr   (+)    0       [1 ,2 ,3 ,4] -- 10
3   foldr   (*)    1       [1 ,2 ,3 ,4] -- 24
4   foldr   (++)   []      [[1] , [1 ,2]] -- [1 ,1 ,2]
5   foldr   (&&)   True     [True , False , True] -- False
6   foldr   (||)   False   [True , False , True] -- True
7
Monoids: Simple "Natural" Examples
                           Listing 11: Haskell
1   --      OP      ID      List
2   foldr   (+)    0       [1 ,2 ,3 ,4] -- 10
3   foldr   (*)    1       [1 ,2 ,3 ,4] -- 24
4   foldr   (++)   []      [[1] , [1 ,2]] -- [1 ,1 ,2]
5   foldr   (&&)   True     [True , False , True] -- False
6   foldr   (||)   False   [True , False , True] -- True
7
Monoids: Simple "Natural" Examples
                           Listing 13: Haskell
1   --      OP      ID      List
2   foldr   (+)    0       [1 ,2 ,3 ,4] -- 10
3   foldr   (*)    1       [1 ,2 ,3 ,4] -- 24
4   foldr   (++)   []      [[1] , [1 ,2]] -- [1 ,1 ,2]
5   foldr   (&&)   True     [True , False , True] -- False
6   foldr   (||)   False   [True , False , True] -- True
7
Monoids: Simple "Natural" Examples
                        Listing 15: Haskell
1   --     OP    ID      List
2   foldr (+) 0         [1 ,2 ,3 ,4] -- 10
3   foldr (*) 1         [1 ,2 ,3 ,4] -- 24
4   foldr (++) []       [[1] , [1 ,2]] -- [1 ,1 ,2]
5   foldr (&&) True      [True , False , True] -- False
6   foldr (||) False    [True , False , True] -- True
7   mconcat = foldr mappend mempty
Monoids: Simple "Natural" Examples
                         Listing 17: Haskell
1   --     OP    ID      List
2   foldr (+) 0         [1 ,2 ,3 ,4] -- 10
3   foldr (*) 1         [1 ,2 ,3 ,4] -- 24
4   foldr (++) []       [[1] , [1 ,2]] -- [1 ,1 ,2]
5   foldr (&&) True      [True , False , True] -- False
6   foldr (||) False    [True , False , True] -- True
7   mconcat = foldr mappend mempty

                   Listing 18: Same in Scala: WTF?
1   List (1 ,2 ,3 ,4). foldRight (0)(_+_) // 10
2   List (1 ,2 ,3 ,4). foldRight (1)(_*_) // 24
3   List(List (1), List (1 ,2)). foldRight (List[Int ]())( _++_)
4   List(true ,false ,true ). foldRight (true )(_&&_)
5   List(true ,false ,true ). foldRight ( false )(_||_)
Monoids: Define Your Own (Haskell)
                  Listing 19: Haskell Monoid Definition
 1   import Data. Monoid
 2
 3   data Asset = Cash Int
 4               | Receivables Int ...
 5   data Liability = NotesPayable Int
 6                   | AccountsPayable Int ...
 7   -- naive , but illustrative
 8   data BalSheet = BalSheet [ Asset ] [ Liability ]
 9
10   instance Monoid BalSheet where
11     mempty :: m
12     mempty = BalSheet [] []
13     mappend :: m -> m -> m
14     mappend ( BalSheet a1 l1) ( BalSheet a2 l2) =
15       BalSheet ( mappend a1 a2) ( mappend l1 l2)
Monoids: Define Your Own (Scala)
                  Listing 20: Scalaz Monoid Definition
 1   import scalaz ._; import Scalaz ._;
 2
 3   // naive , but illustrative
 4   case class Portfolio ( positions : Seq[ Position ])
 5   object Portfolio {
 6     implicit val portfolioMonoid =
 7     new Monoid [ Portfolio ] {
 8       def append (p1: Portfolio , p2: Portfolio ) =
 9         Portfolio ( append (p1.positions , p2. positions ))
10       def zero = Portfolio (Seq. empty )
11     }
12   }
Monoids: So what?
  Properties "Interface"
  Once you understand one monoid, you understand them all; simpler
  layers => simpler tests


  Type Safe & Type Expressive
  Can mappend A s but not a A and a B where A ! = B and
  myCalc :: Monoid a => a -> b


  Generic Functions
  e.g. consolidate = foldr mappend mempty


  Highly Applicable
  Look around your domain. Do you see Monoids Everywhere™ yet?
Monoids: So what?
  Properties "Interface"
  Once you understand one monoid, you understand them all; simpler
  layers => simpler tests


  Type Safe & Type Expressive
  Can mappend A s but not a A and a B where A ! = B and
  myCalc :: Monoid a => a -> b


  Generic Functions
  e.g. consolidate = foldr mappend mempty


  Highly Applicable
  Look around your domain. Do you see Monoids Everywhere™ yet?
Monoids: So what?
  Properties "Interface"
  Once you understand one monoid, you understand them all; simpler
  layers => simpler tests


  Type Safe & Type Expressive
  Can mappend A s but not a A and a B where A ! = B and
  myCalc :: Monoid a => a -> b


  Generic Functions
  e.g. consolidate = foldr mappend mempty


  Highly Applicable
  Look around your domain. Do you see Monoids Everywhere™ yet?
Monoids: So what?
  Properties "Interface"
  Once you understand one monoid, you understand them all; simpler
  layers => simpler tests


  Type Safe & Type Expressive
  Can mappend A s but not a A and a B where A ! = B and
  myCalc :: Monoid a => a -> b


  Generic Functions
  e.g. consolidate = foldr mappend mempty


  Highly Applicable
  Look around your domain. Do you see Monoids Everywhere™ yet?
Monoids: But . . .

  Types With Multiple Monoids
  More boilerplate though usually manageable. e.g.

             Listing 21: Haskell Monoid Typeclass Definition
    1   import Data. Monoid
    2   toSums = map Sum
    3   mconcat $ toSums [1 ,2 ,3 ,4] -- 10
    4
    5   toAlls = map All
    6   getAll $ mconcat $ toAlls [True , False , True]

  Think!
  Does it make sense to declare Vector as a Monoid in Haskell?
Monoids: But . . .

  Types With Multiple Monoids
  More boilerplate though usually manageable. e.g.

             Listing 22: Haskell Monoid Typeclass Definition
    1   import Data. Monoid
    2   toSums = map Sum
    3   mconcat $ toSums [1 ,2 ,3 ,4] -- 10
    4
    5   toAlls = map All
    6   getAll $ mconcat $ toAlls [True , False , True]

  Think!
  Does it make sense to declare Vector as a Monoid in Haskell?
Automatic Optimal Pipelining
http://informatikr.com/2012/redis-pipelining.html

                          Listing 23: Pipelining in Jedis
  1 jedis . pipelined (new PipelineBlock () {
  2   public void execute () {
  3     incr(" hit_count ");
  4     get(" mbbx6spp : repos_count ");
  5   }
  6 });
Automatic Optimal Pipelining
http://informatikr.com/2012/redis-pipelining.html

                          Listing 25: Pipelining in Jedis
  1 jedis . pipelined (new PipelineBlock () {
  2   public void execute () {
  3     incr(" hit_count ");
  4     get(" mbbx6spp : repos_count ");
  5   }
  6 });


                     Listing 26: Automatic Pipelining in Hedis
  1 runRedis conn $ do
  2   hits <- incr " hit_count "
  3   repos <- get " mbbx6spp : repos_count "
  4   liftIO $ print (hits , repos )
Monoids: Other Fun Examples

  Log Priorities / Filters in bittorrent
  http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html




  Associative Alpha Blending
  http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/




  Writer Monad Accumulator
  factorial ::                  Integer -> Writer (Sum Integer) Integer


  Tree in Data.Git module of hit package
Monoids: Other Fun Examples

  Log Priorities / Filters in bittorrent
  http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html




  Associative Alpha Blending
  http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/




  Writer Monad Accumulator
  factorial ::                  Integer -> Writer (Sum Integer) Integer


  Tree in Data.Git module of hit package
Monoids: Other Fun Examples

  Log Priorities / Filters in bittorrent
  http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html




  Associative Alpha Blending
  http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/




  Writer Monad Accumulator
  factorial ::                  Integer -> Writer (Sum Integer) Integer


  Tree in Data.Git module of hit package
Monoids: Other Fun Examples

  Log Priorities / Filters in bittorrent
  http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html




  Associative Alpha Blending
  http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/




  Writer Monad Accumulator
  factorial ::                  Integer -> Writer (Sum Integer) Integer


  Tree in Data.Git module of hit package
Monoids: Relationships

  Monoid v => Map k v also monoid


  All monoids are semigroups
  Semigroup is monoid minus identity requirement


  All groups are monoids
  Monoid is group minus inverse unary operator requirement


  Free Structures
  Get (money for nothing? and) monoids for free
Monoids: Relationships

  Monoid v => Map k v also monoid


  All monoids are semigroups
  Semigroup is monoid minus identity requirement


  All groups are monoids
  Monoid is group minus inverse unary operator requirement


  Free Structures
  Get (money for nothing? and) monoids for free
Monoids: Relationships

  Monoid v => Map k v also monoid


  All monoids are semigroups
  Semigroup is monoid minus identity requirement


  All groups are monoids
  Monoid is group minus inverse unary operator requirement


  Free Structures
  Get (money for nothing? and) monoids for free
Monoids: Relationships

  Monoid v => Map k v also monoid


  All monoids are semigroups
  Semigroup is monoid minus identity requirement


  All groups are monoids
  Monoid is group minus inverse unary operator requirement


  Free Structures
  Get (money for nothing? and) monoids for free
Monoids: Relationships

Monads & Monoids




                         .
Monoids: Relationships

Monads & Monoids
A monad over X is the




                         .
Monoids: Relationships

Monads & Monoids
A monad over X is the

monoid in category of endofunctors of X




                                          .
Monoids: Relationships

Monads & Monoids
A monad over X is the

monoid in category of endofunctors of X

with binary operator as composition
(of endofunctors)

                                          .
Monoids: Relationships

Monads & Monoids
A monad over X is the

monoid in category of endofunctors of X

with binary operator as composition
(of endofunctors)

and identity being the identity endofunctor.
Homework




           What is an Endofunctor?
Questions?




        Figure:   http://www.flickr.com/photos/42682395@N04/




         @FunAlgebra
                    @SusanPotter
Bonus: References / Resources
     Channel 9 Lectures (Erik Meijer)
     http://channel9.msdn.com/Shows/Going+Deep/

     Lecture-Series-Erik-Meijer-Functional-Programming-Fundamentals-Chapter-1




     The Catsters
     http://www.youtube.com/thecatsters




     Haskell Reddit
     http://www.reddit.com/r/haskell/




     Haskell Cafe
     http://www.haskell.org/mailman/listinfo/haskell-cafe




     Scalaz Mailing List
     https://groups.google.com/forum/?fromgroups#!forum/scalaz

Contenu connexe

Tendances

Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingDavid Muñoz Díaz
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerDavid Muñoz Díaz
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1Hackraft
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functionalHackraft
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the worldDavid Muñoz Díaz
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)Yeshwanth Kumar
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 

Tendances (20)

Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
GUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programmingGUL UC3M - Introduction to functional programming
GUL UC3M - Introduction to functional programming
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
RESTful API using scalaz (3)
RESTful API using scalaz (3)RESTful API using scalaz (3)
RESTful API using scalaz (3)
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Collection v3
Collection v3Collection v3
Collection v3
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Collection Core Concept
Collection Core ConceptCollection Core Concept
Collection Core Concept
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 

En vedette

From Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSSusan Potter
 
Constraint Programming in Haskell
Constraint Programming in HaskellConstraint Programming in Haskell
Constraint Programming in HaskellDavid Overton
 
Dynamo: Not Just For Datastores
Dynamo: Not Just For DatastoresDynamo: Not Just For Datastores
Dynamo: Not Just For DatastoresSusan Potter
 
Link Walking with Riak
Link Walking with RiakLink Walking with Riak
Link Walking with RiakSusan Potter
 
Ricon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak PipeRicon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak PipeSusan Potter
 
Writing Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScriptWriting Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScriptSusan Potter
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016Susan Potter
 
Distributed Developer Workflows using Git
Distributed Developer Workflows using GitDistributed Developer Workflows using Git
Distributed Developer Workflows using GitSusan Potter
 
Designing for Concurrency
Designing for ConcurrencyDesigning for Concurrency
Designing for ConcurrencySusan Potter
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignRyan Riley
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monadskenbot
 
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle TreesModern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle TreesLorenzo Alberton
 
Scaling Teams, Processes and Architectures
Scaling Teams, Processes and ArchitecturesScaling Teams, Processes and Architectures
Scaling Teams, Processes and ArchitecturesLorenzo Alberton
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!kenbot
 
Scalable Architectures - Taming the Twitter Firehose
Scalable Architectures - Taming the Twitter FirehoseScalable Architectures - Taming the Twitter Firehose
Scalable Architectures - Taming the Twitter FirehoseLorenzo Alberton
 
Graphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks AgeGraphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks AgeLorenzo Alberton
 
The Art of Scalability - Managing growth
The Art of Scalability - Managing growthThe Art of Scalability - Managing growth
The Art of Scalability - Managing growthLorenzo Alberton
 
The other side of functional programming: Haskell for Erlang people
The other side of functional programming: Haskell for Erlang peopleThe other side of functional programming: Haskell for Erlang people
The other side of functional programming: Haskell for Erlang peopleBryan O'Sullivan
 
NoSQL Databases: Why, what and when
NoSQL Databases: Why, what and whenNoSQL Databases: Why, what and when
NoSQL Databases: Why, what and whenLorenzo Alberton
 
Monitoring at scale - Intuitive dashboard design
Monitoring at scale - Intuitive dashboard designMonitoring at scale - Intuitive dashboard design
Monitoring at scale - Intuitive dashboard designLorenzo Alberton
 

En vedette (20)

From Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOS
 
Constraint Programming in Haskell
Constraint Programming in HaskellConstraint Programming in Haskell
Constraint Programming in Haskell
 
Dynamo: Not Just For Datastores
Dynamo: Not Just For DatastoresDynamo: Not Just For Datastores
Dynamo: Not Just For Datastores
 
Link Walking with Riak
Link Walking with RiakLink Walking with Riak
Link Walking with Riak
 
Ricon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak PipeRicon/West 2013: Adventures with Riak Pipe
Ricon/West 2013: Adventures with Riak Pipe
 
Writing Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScriptWriting Bullet-Proof Javascript: By Using CoffeeScript
Writing Bullet-Proof Javascript: By Using CoffeeScript
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
 
Distributed Developer Workflows using Git
Distributed Developer Workflows using GitDistributed Developer Workflows using Git
Distributed Developer Workflows using Git
 
Designing for Concurrency
Designing for ConcurrencyDesigning for Concurrency
Designing for Concurrency
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle TreesModern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
Modern Algorithms and Data Structures - 1. Bloom Filters, Merkle Trees
 
Scaling Teams, Processes and Architectures
Scaling Teams, Processes and ArchitecturesScaling Teams, Processes and Architectures
Scaling Teams, Processes and Architectures
 
Your data structures are made of maths!
Your data structures are made of maths!Your data structures are made of maths!
Your data structures are made of maths!
 
Scalable Architectures - Taming the Twitter Firehose
Scalable Architectures - Taming the Twitter FirehoseScalable Architectures - Taming the Twitter Firehose
Scalable Architectures - Taming the Twitter Firehose
 
Graphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks AgeGraphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks Age
 
The Art of Scalability - Managing growth
The Art of Scalability - Managing growthThe Art of Scalability - Managing growth
The Art of Scalability - Managing growth
 
The other side of functional programming: Haskell for Erlang people
The other side of functional programming: Haskell for Erlang peopleThe other side of functional programming: Haskell for Erlang people
The other side of functional programming: Haskell for Erlang people
 
NoSQL Databases: Why, what and when
NoSQL Databases: Why, what and whenNoSQL Databases: Why, what and when
NoSQL Databases: Why, what and when
 
Monitoring at scale - Intuitive dashboard design
Monitoring at scale - Intuitive dashboard designMonitoring at scale - Intuitive dashboard design
Monitoring at scale - Intuitive dashboard design
 

Similaire à Functional Algebra: Monoids Applied

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
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and LibrariesVenugopalavarma Raja
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scalaMichel Perez
 
Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWorkhorse Computing
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyVysakh Sreenivasan
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキストOpt Technologies
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10Kousuke Ruichi
 

Similaire à Functional Algebra: Monoids Applied (20)

Practical cats
Practical catsPractical cats
Practical cats
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
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
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 
Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility Modules
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10
 

Plus de Susan Potter

Thinking in Properties
Thinking in PropertiesThinking in Properties
Thinking in PropertiesSusan Potter
 
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)Susan Potter
 
From Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons LearnedFrom Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons LearnedSusan Potter
 
Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...Susan Potter
 
Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)Susan Potter
 
Deploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweatDeploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweatSusan Potter
 

Plus de Susan Potter (7)

Thinking in Properties
Thinking in PropertiesThinking in Properties
Thinking in Properties
 
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)Champaign-Urbana Javascript Meetup Talk (Jan 2020)
Champaign-Urbana Javascript Meetup Talk (Jan 2020)
 
From Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons LearnedFrom Zero to Haskell: Lessons Learned
From Zero to Haskell: Lessons Learned
 
Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...Dynamically scaling a political news and activism hub (up to 5x the traffic i...
Dynamically scaling a political news and activism hub (up to 5x the traffic i...
 
Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)
 
Twitter4R OAuth
Twitter4R OAuthTwitter4R OAuth
Twitter4R OAuth
 
Deploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweatDeploying distributed software services to the cloud without breaking a sweat
Deploying distributed software services to the cloud without breaking a sweat
 

Functional Algebra: Monoids Applied

  • 1. Functional Algebra Monoids Applied Susan Potter Nov 10, 2012
  • 3. OMG, Algebra? FML.. . . Figure: Chill! Algebra is just a domain specific language
  • 4. % whoami Figure: From OO patterns to FP abstractions
  • 5. Monoids: What are they? An abstraction (laws) not a design pattern (forces, context, . . . ) Algebraic structure . . . over a set with a binary operator and an identity element Accumulator . . . Its sole purpose Special case category . . . with only one object
  • 6. Monoids: What are they? An abstraction (laws) not a design pattern (forces, context, . . . ) Algebraic structure . . . over a set with a binary operator and an identity element Accumulator . . . Its sole purpose Special case category . . . with only one object
  • 7. Monoids: What are they? An abstraction (laws) not a design pattern (forces, context, . . . ) Algebraic structure . . . over a set with a binary operator and an identity element Accumulator . . . Its sole purpose Special case category . . . with only one object
  • 8. Monoids: What are they? An abstraction (laws) not a design pattern (forces, context, . . . ) Algebraic structure . . . over a set with a binary operator and an identity element Accumulator . . . Its sole purpose Special case category . . . with only one object
  • 9. Monoids: Typeclasses Listing 1: Haskell Monoid Typeclass Definition 1 -- | In Haskell Prelude Data. Monoid 2 class Monoid a where 3 mempty :: a -- identity 4 mappend :: a -> a -> a -- binary op 5 mconcat :: [a] -> a -- helper Listing 2: Scalaz Monoid Trait Definition 1 // Scalaz 7’s Monoid typeclass definition , kinda 2 trait Monoid [A] extends Semigroup [A] { self => 3 def zero: A /* identity */ 4 def append(x: A, y: => A): A /* binary op */ 5 } 6 // from SemigroupOps [A] ... 7 final def |+|(other: => A): A = A.append(self, other)
  • 10. Monoids: Typeclasses Listing 3: Haskell Monoid Typeclass Definition 1 -- | In Haskell Prelude Data. Monoid 2 class Monoid a where 3 mempty :: a -- identity 4 mappend :: a -> a -> a -- binary op 5 mconcat :: [a] -> a -- helper Listing 4: Scalaz Monoid Trait Definition 1 // Scalaz 7’s Monoid typeclass definition , kinda 2 trait Monoid [A] extends Semigroup [A] { self => 3 def zero: A /* identity */ 4 def append(x: A, y: => A): A /* binary op */ 5 } 6 // from SemigroupOps [A] ... 7 final def |+|(other: => A): A = A.append(self, other)
  • 11. Monoids: Typeclasses Listing 5: Haskell Monoid Typeclass Definition 1 -- | In Haskell Prelude Data. Monoid 2 class Monoid a where 3 mempty :: a -- identity 4 mappend :: a -> a -> a -- binary op 5 mconcat :: [a] -> a -- helper Listing 6: Scalaz Monoid Trait Definition 1 // Scalaz 7’s Monoid typeclass definition , kinda 2 trait Monoid [A] extends Semigroup [A] { self => 3 def zero: A /* identity */ 4 def append(x: A, y: => A): A /* binary op */ 5 } 6 // from SemigroupOps [A] ... 7 final def |+|(other: => A): A = A.append(self, other)
  • 12. Monoids: Typeclasses Listing 7: Haskell Monoid Typeclass Definition 1 -- | In Haskell Prelude Data. Monoid 2 class Monoid a where 3 mempty :: a -- identity 4 mappend :: a -> a -> a -- binary op 5 mconcat :: [a] -> a -- helper Listing 8: Scalaz Monoid Trait Definition 1 // Scalaz 7’s Monoid typeclass definition , kinda 2 trait Monoid [A] extends Semigroup [A] { self => 3 def zero: A /* identity */ 4 def append(x: A, y: => A): A /* binary op */ 5 } 6 // from SemigroupOps [A] ... 7 final def |+|(other: => A): A = A.append(self, other)
  • 13. Monoids: Laws Closure: ∀a, b ∈ S : ab ∈ S for all a and b in set S, the result of a and b given to the binary operator is also in set S. Associativity: ∀a, b, c ∈ S : (ab)c = a(bc) for all a, b, and c in set S, either binary operator can be evaluated first to produce same result. Identity: ∃e ∈ S : ∀a ∈ S : ea = a = ae there exists an e in set S such that for all a in set S ea evaluates to a and is equal to ae
  • 14. Monoids: Laws Closure: ∀a, b ∈ S : ab ∈ S for all a and b in set S, the result of a and b given to the binary operator is also in set S. Associativity: ∀a, b, c ∈ S : (ab)c = a(bc) for all a, b, and c in set S, either binary operator can be evaluated first to produce same result. Identity: ∃e ∈ S : ∀a ∈ S : ea = a = ae there exists an e in set S such that for all a in set S ea evaluates to a and is equal to ae
  • 15. Monoids: Laws Closure: ∀a, b ∈ S : ab ∈ S for all a and b in set S, the result of a and b given to the binary operator is also in set S. Associativity: ∀a, b, c ∈ S : (ab)c = a(bc) for all a, b, and c in set S, either binary operator can be evaluated first to produce same result. Identity: ∃e ∈ S : ∀a ∈ S : ea = a = ae there exists an e in set S such that for all a in set S ea evaluates to a and is equal to ae
  • 16. Monoids: Properties (Haskell) 1 -- property based tests for monoid "laws" 2 -- does not compile yet; must specify type a 3 module Tests where 4 import Test. QuickCheck ( quickCheck ) 5 6 -- closure law verified by type system 7 8 propMonoidAssoc :: Monoid a => a -> a -> a -> Bool 9 propMonoidAssoc x y z = 10 mappend ( mappend x y) z == mappend x ( mappend y z) 11 12 propMonoidIdent :: Monoid a => a -> Bool 13 propMonoidIdent x = 14 mappend mempty x == x && mappend x mempty == x
  • 17. Monoids: Simple "Natural" Examples Listing 9: Haskell 1 -- OP ID List 2 foldr (+) 0 [1 ,2 ,3 ,4] -- 10 3 foldr (*) 1 [1 ,2 ,3 ,4] -- 24 4 foldr (++) [] [[1] , [1 ,2]] -- [1 ,1 ,2] 5 foldr (&&) True [True , False , True] -- False 6 foldr (||) False [True , False , True] -- True 7
  • 18. Monoids: Simple "Natural" Examples Listing 11: Haskell 1 -- OP ID List 2 foldr (+) 0 [1 ,2 ,3 ,4] -- 10 3 foldr (*) 1 [1 ,2 ,3 ,4] -- 24 4 foldr (++) [] [[1] , [1 ,2]] -- [1 ,1 ,2] 5 foldr (&&) True [True , False , True] -- False 6 foldr (||) False [True , False , True] -- True 7
  • 19. Monoids: Simple "Natural" Examples Listing 13: Haskell 1 -- OP ID List 2 foldr (+) 0 [1 ,2 ,3 ,4] -- 10 3 foldr (*) 1 [1 ,2 ,3 ,4] -- 24 4 foldr (++) [] [[1] , [1 ,2]] -- [1 ,1 ,2] 5 foldr (&&) True [True , False , True] -- False 6 foldr (||) False [True , False , True] -- True 7
  • 20. Monoids: Simple "Natural" Examples Listing 15: Haskell 1 -- OP ID List 2 foldr (+) 0 [1 ,2 ,3 ,4] -- 10 3 foldr (*) 1 [1 ,2 ,3 ,4] -- 24 4 foldr (++) [] [[1] , [1 ,2]] -- [1 ,1 ,2] 5 foldr (&&) True [True , False , True] -- False 6 foldr (||) False [True , False , True] -- True 7 mconcat = foldr mappend mempty
  • 21. Monoids: Simple "Natural" Examples Listing 17: Haskell 1 -- OP ID List 2 foldr (+) 0 [1 ,2 ,3 ,4] -- 10 3 foldr (*) 1 [1 ,2 ,3 ,4] -- 24 4 foldr (++) [] [[1] , [1 ,2]] -- [1 ,1 ,2] 5 foldr (&&) True [True , False , True] -- False 6 foldr (||) False [True , False , True] -- True 7 mconcat = foldr mappend mempty Listing 18: Same in Scala: WTF? 1 List (1 ,2 ,3 ,4). foldRight (0)(_+_) // 10 2 List (1 ,2 ,3 ,4). foldRight (1)(_*_) // 24 3 List(List (1), List (1 ,2)). foldRight (List[Int ]())( _++_) 4 List(true ,false ,true ). foldRight (true )(_&&_) 5 List(true ,false ,true ). foldRight ( false )(_||_)
  • 22. Monoids: Define Your Own (Haskell) Listing 19: Haskell Monoid Definition 1 import Data. Monoid 2 3 data Asset = Cash Int 4 | Receivables Int ... 5 data Liability = NotesPayable Int 6 | AccountsPayable Int ... 7 -- naive , but illustrative 8 data BalSheet = BalSheet [ Asset ] [ Liability ] 9 10 instance Monoid BalSheet where 11 mempty :: m 12 mempty = BalSheet [] [] 13 mappend :: m -> m -> m 14 mappend ( BalSheet a1 l1) ( BalSheet a2 l2) = 15 BalSheet ( mappend a1 a2) ( mappend l1 l2)
  • 23. Monoids: Define Your Own (Scala) Listing 20: Scalaz Monoid Definition 1 import scalaz ._; import Scalaz ._; 2 3 // naive , but illustrative 4 case class Portfolio ( positions : Seq[ Position ]) 5 object Portfolio { 6 implicit val portfolioMonoid = 7 new Monoid [ Portfolio ] { 8 def append (p1: Portfolio , p2: Portfolio ) = 9 Portfolio ( append (p1.positions , p2. positions )) 10 def zero = Portfolio (Seq. empty ) 11 } 12 }
  • 24. Monoids: So what? Properties "Interface" Once you understand one monoid, you understand them all; simpler layers => simpler tests Type Safe & Type Expressive Can mappend A s but not a A and a B where A ! = B and myCalc :: Monoid a => a -> b Generic Functions e.g. consolidate = foldr mappend mempty Highly Applicable Look around your domain. Do you see Monoids Everywhere™ yet?
  • 25. Monoids: So what? Properties "Interface" Once you understand one monoid, you understand them all; simpler layers => simpler tests Type Safe & Type Expressive Can mappend A s but not a A and a B where A ! = B and myCalc :: Monoid a => a -> b Generic Functions e.g. consolidate = foldr mappend mempty Highly Applicable Look around your domain. Do you see Monoids Everywhere™ yet?
  • 26. Monoids: So what? Properties "Interface" Once you understand one monoid, you understand them all; simpler layers => simpler tests Type Safe & Type Expressive Can mappend A s but not a A and a B where A ! = B and myCalc :: Monoid a => a -> b Generic Functions e.g. consolidate = foldr mappend mempty Highly Applicable Look around your domain. Do you see Monoids Everywhere™ yet?
  • 27. Monoids: So what? Properties "Interface" Once you understand one monoid, you understand them all; simpler layers => simpler tests Type Safe & Type Expressive Can mappend A s but not a A and a B where A ! = B and myCalc :: Monoid a => a -> b Generic Functions e.g. consolidate = foldr mappend mempty Highly Applicable Look around your domain. Do you see Monoids Everywhere™ yet?
  • 28. Monoids: But . . . Types With Multiple Monoids More boilerplate though usually manageable. e.g. Listing 21: Haskell Monoid Typeclass Definition 1 import Data. Monoid 2 toSums = map Sum 3 mconcat $ toSums [1 ,2 ,3 ,4] -- 10 4 5 toAlls = map All 6 getAll $ mconcat $ toAlls [True , False , True] Think! Does it make sense to declare Vector as a Monoid in Haskell?
  • 29. Monoids: But . . . Types With Multiple Monoids More boilerplate though usually manageable. e.g. Listing 22: Haskell Monoid Typeclass Definition 1 import Data. Monoid 2 toSums = map Sum 3 mconcat $ toSums [1 ,2 ,3 ,4] -- 10 4 5 toAlls = map All 6 getAll $ mconcat $ toAlls [True , False , True] Think! Does it make sense to declare Vector as a Monoid in Haskell?
  • 30. Automatic Optimal Pipelining http://informatikr.com/2012/redis-pipelining.html Listing 23: Pipelining in Jedis 1 jedis . pipelined (new PipelineBlock () { 2 public void execute () { 3 incr(" hit_count "); 4 get(" mbbx6spp : repos_count "); 5 } 6 });
  • 31. Automatic Optimal Pipelining http://informatikr.com/2012/redis-pipelining.html Listing 25: Pipelining in Jedis 1 jedis . pipelined (new PipelineBlock () { 2 public void execute () { 3 incr(" hit_count "); 4 get(" mbbx6spp : repos_count "); 5 } 6 }); Listing 26: Automatic Pipelining in Hedis 1 runRedis conn $ do 2 hits <- incr " hit_count " 3 repos <- get " mbbx6spp : repos_count " 4 liftIO $ print (hits , repos )
  • 32. Monoids: Other Fun Examples Log Priorities / Filters in bittorrent http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html Associative Alpha Blending http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/ Writer Monad Accumulator factorial :: Integer -> Writer (Sum Integer) Integer Tree in Data.Git module of hit package
  • 33. Monoids: Other Fun Examples Log Priorities / Filters in bittorrent http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html Associative Alpha Blending http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/ Writer Monad Accumulator factorial :: Integer -> Writer (Sum Integer) Integer Tree in Data.Git module of hit package
  • 34. Monoids: Other Fun Examples Log Priorities / Filters in bittorrent http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html Associative Alpha Blending http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/ Writer Monad Accumulator factorial :: Integer -> Writer (Sum Integer) Integer Tree in Data.Git module of hit package
  • 35. Monoids: Other Fun Examples Log Priorities / Filters in bittorrent http://jlouisramblings.blogspot.com/2010/02/how-logging-is-performed-in-haskell.html Associative Alpha Blending http://lukepalmer.wordpress.com/2010/02/05/associative-alpha-blending/ Writer Monad Accumulator factorial :: Integer -> Writer (Sum Integer) Integer Tree in Data.Git module of hit package
  • 36. Monoids: Relationships Monoid v => Map k v also monoid All monoids are semigroups Semigroup is monoid minus identity requirement All groups are monoids Monoid is group minus inverse unary operator requirement Free Structures Get (money for nothing? and) monoids for free
  • 37. Monoids: Relationships Monoid v => Map k v also monoid All monoids are semigroups Semigroup is monoid minus identity requirement All groups are monoids Monoid is group minus inverse unary operator requirement Free Structures Get (money for nothing? and) monoids for free
  • 38. Monoids: Relationships Monoid v => Map k v also monoid All monoids are semigroups Semigroup is monoid minus identity requirement All groups are monoids Monoid is group minus inverse unary operator requirement Free Structures Get (money for nothing? and) monoids for free
  • 39. Monoids: Relationships Monoid v => Map k v also monoid All monoids are semigroups Semigroup is monoid minus identity requirement All groups are monoids Monoid is group minus inverse unary operator requirement Free Structures Get (money for nothing? and) monoids for free
  • 41. Monoids: Relationships Monads & Monoids A monad over X is the .
  • 42. Monoids: Relationships Monads & Monoids A monad over X is the monoid in category of endofunctors of X .
  • 43. Monoids: Relationships Monads & Monoids A monad over X is the monoid in category of endofunctors of X with binary operator as composition (of endofunctors) .
  • 44. Monoids: Relationships Monads & Monoids A monad over X is the monoid in category of endofunctors of X with binary operator as composition (of endofunctors) and identity being the identity endofunctor.
  • 45. Homework What is an Endofunctor?
  • 46. Questions? Figure: http://www.flickr.com/photos/42682395@N04/ @FunAlgebra @SusanPotter
  • 47. Bonus: References / Resources Channel 9 Lectures (Erik Meijer) http://channel9.msdn.com/Shows/Going+Deep/ Lecture-Series-Erik-Meijer-Functional-Programming-Fundamentals-Chapter-1 The Catsters http://www.youtube.com/thecatsters Haskell Reddit http://www.reddit.com/r/haskell/ Haskell Cafe http://www.haskell.org/mailman/listinfo/haskell-cafe Scalaz Mailing List https://groups.google.com/forum/?fromgroups#!forum/scalaz