Last active
August 29, 2015 14:21
-
-
Save matsu-chara/d69cb610353c84f22767 to your computer and use it in GitHub Desktop.
MonadPlus(Monad + Monoid) http://d.hatena.ne.jp/sirocco/20110415/1302856463
This file contains hidden or 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
import Control.Monad | |
-- list | |
:{ | |
do | |
x <- [1,2,3] `mplus` [4,5,6] | |
return x -- [1, 2, 3, 4, 5, 6] | |
:} | |
:{ | |
do | |
x <- Nothing `mplus` Just 2 | |
return x -- Just 2 | |
:} | |
-- リストをなぞって条件に一致した値をMonadPlusで返す。 | |
:{ | |
let {; | |
mLsearch :: MonadPlus m => (Int -> Bool) -> [Int] -> m Int; | |
mLsearch _ [] = mzero; | |
mLsearch isCond (x:xs) | |
| isCond x = return x `mplus` mLsearch isCond xs | |
| otherwise = mLsearch isCond xs | |
} | |
:} | |
-- リストで返す。 | |
mLsearch (==10) [0..20] :: [Int] -- => [10] | |
mLsearch (>10) [0..20] :: [Int] -- => [11,12,13,14,15,16,17,18,19,20] | |
mLsearch (==99) [0..20] :: [Int] -- => [] | |
-- Maybeで返す。 | |
mLsearch (==10) [0..20] :: Maybe Int -- => Just 10 | |
mLsearch (==100) [0..20] :: Maybe Int -- => Nothing | |
mLsearch (>100) [0..20] :: Maybe Int -- => Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment