第10ç«
ã¨ã³ãã£ãã£
- å¤æ°
- åã³ã³ã¹ãã©ã¯ã¿
- ãã¼ã¿ã³ã³ã¹ãã©ã¯ã¿
- ãã£ã¼ã«ãã©ãã«
- åã¯ã©ã¹
- ã¯ã©ã¹ã¡ã½ãã
ã¢ã¸ã¥ã¼ã«å®ç¾©
åºæ¬çãªå½¢
module Repository where
ç¹å®ã®ã¨ã³ãã£ãã£ã®ã¿ã¨ã¯ã¹ãã¼ããã
module Repository (findById, save) where
ãã¼ã¿ã³ã³ã¹ãã©ã¯ã¿ã¼ã®ã¨ã¯ã¹ãã¼ã
module Repository (Repo(UserRepo, TweetRepo), findById, save) where data Repo = UserRepo | TweetRepo
åã³ã³ã¹ãã©ã¯ã¿ã¼ã«å¯¾å¿ãããã¼ã¿ã³ã³ã¹ãã©ã¯ã¿ã¼ãã¨ã¯ã¹ãã¼ãããå ´å
module Repository (Repo(..), findById, save) where
ã¤ã³ãã¼ãããã¢ã¸ã¥ã¼ã«ã®ã¨ã³ãã£ãã£ãã¨ã¯ã¹ãã¼ãããå ´å
module Repository (module Data.List.map Repo(..), findById, save) where import Data.List.map
ã¤ã³ãã¼ã
-- Data.Listã¢ã¸ã¥ã¼ã«ãã¤ã³ãã¼ã import Data.List -- ç¹å®ã®ã¨ã³ãã£ãã£ãã¤ã³ãã¼ãããã³ç¹å®ã®ã¨ã³ãã£ãã£(ä¸ã®ä¾ã§ã¯join)ãã¤ã³ãã¼ããé²æ¢ import Control.Monad (Monad, Maybe) hiding (join) -- å®å ¨ä¿®é£¾åã§ã¤ã³ãã¼ãããã¨å®å ¨ä¿®é£¾åã§ã®ã¿é¢æ°ãªã©ã«ã¢ã¯ã»ã¹ããããã«ãªã(ååè¡çªã®åé¿) import qualified Text.Regex -- å¥åãä¸ãã¦ã¤ã³ãã¼ã import GHC.IO.Encoding as Enc
第11ç«
Monad
Monadã¯ã©ã¹
class Monad m where (>>=):: m a -> (a -> m b) -> m b return:: a -> m a
ã¢ããå
ã¢ããã¯ä¸è¨ã®æ³åãæºãã
(return x) >>= f == f x m >>= return == m (m >>= f) >>= g == m >>= (\x -> f x >>= g)
Maybe
å¤ã®æç¡ã表ããNothing
ãå¤ãªããJust a
ãå¤ãã
å®ç¾©
data Maybe a = Nothing | Just a deriving (Eq, Ord) instance Monad Maybe where (Just x) >>= f = f x Nothing >>= _ = Nothing return x = Just x
ç°¡åãªMaybe
ã®ä¾
-- dictionaryãç¨æ myMap = [("bar", 1), ("baz", 2), ("foo", 3)] -- æ°åãå¥æ°ãªãJustãå¶æ°ãªãNothing oddNum:: Int -> Maybe Int oddNum n = case (mod n 2) of 1 -> Just n 0 -> Nothing -- main main = do print $ lookup "foo" myMap >>= oddNum -- Just 3 print $ lookup "baz" myMap >>= oddNum -- Nothing print $ lookup "hoge" myMap >>= oddNum -- Nothing
ãªã¹ãMonad
å®ç¾©
instance Monad [] where xs >>= f = concatMap f xs return x = [x]
IO Monad
æ´æ°å¾ã®ä¸çã¨ããããããããã£ããã¨ãããããå¯ä½ç¨ã®ããå¦çã«æ´»ç¨ã§ãããããã