Last active
October 18, 2019 12:42
-
-
Save nobishino/0131b4c540a838de46edee9529cff61a to your computer and use it in GitHub Desktop.
Maybe Monadサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Maybe a (aは任意の型)は「失敗するかもしれない計算」を表す | |
-- f,g,hという3つのMaybeモナド(を返す関数)をつなぐやつ | |
-- f :: Int -> Maybe Int | |
-- g :: Int -> Maybe String | |
-- h :: String -> Maybe () | |
f :: Int -> Maybe Int | |
f n = if n < 10 then Just (n * 3) else Nothing | |
-- *Main> f 3 | |
-- Just 9 | |
-- *Main> f 10 | |
-- Nothing | |
g :: Int -> Maybe String | |
g n = if n < 20 then Just "Okay" else Nothing | |
-- *Main> g 10 | |
-- Just "Okay" | |
-- *Main> g 21 | |
-- Nothing | |
h :: String -> Maybe () | |
h "Okay" = Just () | |
h _ = Nothing | |
-- *Main> h "Hello" | |
-- Hello | |
-- bind演算子 >>= で3つをつなぐ | |
-- (>>=) の関数としての型は次の通り | |
-- *Main> :t (>>=) | |
-- (>>=) :: Monad m => m a -> (a -> m b) -> m b | |
connect :: Int -> Maybe () | |
connect n = f n >>= g >>= h | |
-- 動かすと | |
-- *Main> connect 1 | |
-- Just () | |
-- *Main> connect 10 | |
-- Nothing | |
-- のようになる |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment