我們可以自己實作一個模仿 Maybe 行為的 type:
-- Haskell 語法
data MightBe = NoThanks | Ok a deriving (Eq, Show)
那麼我們可以這樣幫它實作 Monoid 的 typeclass:
-- Haskell 語法
instance Semigroup a => Monoid (MightBe a) where
mempty = NoThanks
mappend (OK x) (OK y) = OK (mappend x y)
mappend x NoThanks = x
mappend NoThanks x = x
-- 試試看
OK (Sum 2) <> OK (Sum 10) -- => OK (Sum {getSum = 12})
OK (Sum 2) <> NoThanks -- -> OK (Sum {getSum = 2})
能不能幫這些東西做出 Monoid 的實體呢?
data Double a a = Double a a
-- 提示,實作上你可能需要幫它加個前題
-- 希望能
(Double (Sum 1) (Sum 2)) <> (Double (Sum 3) (Sum 4)
-- => Double (Sum 4) (Sum 5)
我們想要有個會停在第一個 Stop 的型別:
data Drive a b =
Go a
| Stop b
-- 希望能
Go 1 <> Go 2 -- => Go 2
Go 1 <> Stop 3 -- => Stop 3
Stop 3 <> Go 4 -- => Stop 3
Stop 5 <> Stop 6 -- => Stop 5
註*:程式即證明:柯里-霍華德同構