DAY 23
1
Software Development

## 中綴與前綴

``````-- Haskell 語法
class Semigroup a where
(<>) :: a -> a -> a
...
infixr 6 <>
-----------
class Semigroup a => Monoid a where
...
mappend :: a -> a -> a
...

-- 試試看
[1, 2, 3] <> [4, 5, 6]      -- => [1, 2, 3, 4, 5, 6]

mappend [1, 2, 3] [4, 5, 6] -- => [1, 2, 3, 4, 5, 6]
``````

### 前綴轉中綴，以及反過來

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

``````-- Haskell 語法
Product 2 `mappend` Product 3 -- => Product {getProduct = 6}
``````

## 字串是一種 Monoid 嗎？

1. 字串的單位元素： `""`
``````-- Haskell 語法
"foo" ++ "" == "" ++ "foo" == "foo"
``````

## 串列

``````-- Haskell 語法
[1, 2, 3] ++ [] == [] ++ [1, 2, 3] == [1, 2, 3]
``````

## 試試看

``````-- Haskell 語法
import Data.Monoid -- Data.Monoid 裡也有 Sum 及 Product

-- 在變數或值的後面加上 :: 來手動指定型別

mempty :: Sum Integer -- => Sum {getSum = 0}

mempty :: Product Integer -- => Product {getProduct = 1}

mempty :: [a] -- => []

mempty :: String -- => ""
``````

## 為什麼要費神做這件事？

``````-- 只在型別宣告標記這是個整數乘法，進行合併
foldr mappend mempty ([1, 3, 5] :: [Product Int]) -- => Product {getProduct = 15}

-- 型別為整數加法，進行合併
foldr mappend mempty ([1, 3, 5] :: [Sum Int]) -- => Sum {getSum = 9}

-- 字串的合併
``````

[to be continue]