Friday 3 June 2016

Benefits of Monoid in Haskell

In my previous post, I explaind about monoids. In brief, Monoid is a type class, which specifies a way to combine elements of same type. A monid must satisfy following rules.

In any monoid
a.   (x combineWith y) combineWith z = x xombineWith (y combineWith z), this meta rule is called associativity.
b.   The monoid should contain ‘s’, a special member such that
1.    (x combinesWith s) = x.
2.   (s combinesWith x) = x

For example, + operator is monoid on ideneity element 0.
         a. + satisfies associativity. 10 + (20 + 30) == (10+20) + 30
         b. + has an idenetity value 0. 10 + 0, 0 + 10 return 10

Similarly * is monoid on identity element 1, list is a monoid on [].

Monoid mainly used to combine elements. Since As i said, monoid should satisfy the associativity property, the order of evaluation (left to right, right to left) doesn't matter.


Sample.hs
data Multiplication x = Multiplication x deriving Show

instance Num x => Monoid (Multiplication x) where
    mempty  = Multiplication 1

    mappend (Multiplication x) (Multiplication y) = Multiplication (x * y)

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> mconcat [Multiplication 10, Multiplication 12, Multiplication 14, Multiplication 16]
Multiplication 26880




Previous                                                 Next                                                 Home

No comments:

Post a Comment