DAY 24
1
Software Development

## Maybe 是一種 Monoid 嗎？

``````-- Haskell 語法
-- Maybe Monoid 的型別宣告
instance Semigroup a => Monoid (Maybe a)
``````

### 試試看吧：

``````-- Haskell 語法
Just (Sum 1) <> Just (Sum 2) -- => Just (Sum {getSum = 3})

Just (Sum 1) <> Nothing -- => Just (Sum {getSum = 1})
``````

## 元組是一種 Monoid 嗎？

``````-- Haskell 語法
-- 元組們的 Monoid 的型別宣告
instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) =>
Monoid (a, b, c, d, e)

instance (Monoid a, Monoid b, Monoid c, Monoid d) =>
Monoid (a, b, c, d)

instance (Monoid a, Monoid b, Monoid c) => Monoid (a, b, c)

instance (Monoid a, Monoid b) => Monoid (a, b)

-- 試試看
(Sum 1, Product 2) <> (Sum 2, Product 3)
-- => (Sum {getSum = 3},Product {getProduct = 6})
``````

## 布林值是一種 Monoid 嗎？

``````-- Haskell 語法
(All True) <> (All False) <> (All True)  -- => All {getAll = False}

(Any False) <> (Any False) <> (Any True) -- =>Any {getAny = True}
``````

## 函式是一種 Semigroup 嗎？

``````-- Haskell 語法
f = (+ 1)
g = (* 2)
h = (+ 3)

cf1 = (f . g) . h
cf2 = f . (g . h)

cf1 1 == cf2 1
``````

## 函式是一種 Monoid 嗎？

``````-- Haskell 語法
\x -> x + 1
``````

### 沒作用的函式？

``````-- Haskell 語法
\x -> x
``````

``````-- Haskell 語法
id 1 -- => 1
id True -- => True
``````

### 等一下，其實還有一個前題：

``````-- Haskell 語法
-- 內建：函式 Monoid 的實作
instance Monoid b => Monoid (a -> b) where
mempty _ = mempty
mappend f g x = mappend (f x) (g x)

-- 用用看！
f x = Sum x * 10
g x = Sum x - 1

h = f <> g
h 20 -- => Sum {getSum = 219}
``````

[to be continue]