Skip to content

Instantly share code, notes, and snippets.

@matsu-chara
Last active August 29, 2015 14:21
Show Gist options
  • Save matsu-chara/d69cb610353c84f22767 to your computer and use it in GitHub Desktop.
Save matsu-chara/d69cb610353c84f22767 to your computer and use it in GitHub Desktop.
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