The Typeclassopediaã«ã¯ã以ä¸ã®ãããªæç« ãããã¾ãã
çµå±ãããããèªå¤§åºåã«ãããããããMonadã¯åãªãåã¯ã©ã¹ã«éãã¾ããã
ã¾ããThe Trivial Monadã§ã¯ã以ä¸ã®ããã«è¿°ã¹ããã¦ãã¾ãã
Haskell ã® Monad ã¯åã¯ã©ã¹ã®1ã¤ã§ããHaskell ã®åã¯ã©ã¹ã¯ãè¤æ°ã®åã§å ±éãã API ãå®ãã¾ããã ãããMonad ã¨ããåã¯ã©ã¹ã¨ã¯ãåã®éåã«å¯¾ããå ±éã® API ã§ãã
å ±éã® API ã¨ã¯ãreturn 㨠(>>=) ã®ãã¨ã§ãã
ããè¨ãããã¨ãããã«ããã®å ±éã®APIã使ãã¨ä½ãå¬ããã®ï¼ãã¨ããçåã湧ãã§ãããããã¡ãããå ±éã® API ã使ãå¬ããã¯ãå¾ããåãå¤ããã¨ãã«ãå®è£ ãå¤ããªãã¦ããããã¨ã§ãããã®è¨äºã§ã¯ããã®ä¸ä¾ããè¦ããã¾ãããã
ç§ããMonad ã§å®è£ ãã¦ããã£ããã¨æãããã¨ãããã®ã¯ãã¼ãµã¼ã§ãã®ã§ãä¾ã¨ãã¦ãã¼ãµã¼ãåãä¸ãã¾ããå®è£ ã¯ãè¨äºã®æå¾ã«ç¤ºãã¦ããã¾ãã
Maybe ã使ã£ããã¼ãµã¼
Monad ã¯æèã表ãã¨è¨ããã¾ãã
Maybe ã¯ã失æãããããããªãè¨ç®ãã¨ããæèã表ãã¾ããè¨ãæããã¨ãæåãç¶ããã°è¨ç®ã¯ç¶ããã失æãããªãããã§çµããã¨ããã決å®æ§ãæã¤è¨ç®ã§ãã
ãã¼ãµã¼ã Maybe ãå©ç¨ãã¦å®è£ ãã¦ã¿ã¾ãããã
data Parser a = Parser { parse :: String -> Maybe (a,String) }
ãã®ãã¼ãµã¼ã§ã¯ããã¨ãä»ã«ãããããåè£ããã£ãã¨ãã¦ããè¿ã£ã¦ããçµæã¯1ã¤ã ãã§ãã
parse (string "f" <|> string "foo") "foo" â Just ("f","oo")
ãªã¹ãã使ã£ããã¼ãµã¼
ãªã¹ãã¯ããé決å®æ§ãã¨ããæèã表ãã¾ããé 延è©ä¾¡ã® Haskell ã§ã¯ããããªé£ãã説æã¯ä¸è¦ã§ãåã«å ¨æ¢ç´¢ããã¨ããæå³ã§ãã(ãªã¹ãã¯é 延ããã®ã§ãæåã®åè£ã ããå©ç¨ãããªããä»ã®åè£ã¯æ¢ç´¢ããã¾ããã)
ãã¼ãµã¼ã®å®ç¾©ã Maybe ãããªã¹ãã«å¤ãã¦ã¿ã¾ãããã
data Parser a = Parser { parse :: String -> [(a,String)] }
ãã®ãã¼ãµã¼ã¯ãå®è£ ãã¾ã£ããå¤æ´ããã«åãã¾ãããæå¾ éãã«å ¨æ¢ç´¢ãã¦ããã¾ãã
parse (string "f" <|> string "foo") "foo" â [("f","oo"),("foo","")]
ç¾èã¯ä¸è¦ã«ãããã®æ°æã¡ã«ãªãã¾ãããï¼
ãã¼ãµã¼ã®å®è£
module Parser where import Control.Monad import Control.Applicative ---------------------------------------------------------------- data Parser a = Parser { parse :: String -> Maybe (a,String) } --data Parser a = Parser { parse :: String -> [(a,String)] } ---------------------------------------------------------------- instance Functor Parser where f `fmap` p = return f <*> p instance Applicative Parser where pure = return (<*>) = ap instance Alternative Parser where empty = mzero (<|>) = mplus instance Monad Parser where return a = Parser $ \cs -> return (a,cs) p >>= f = Parser $ \cs -> parse p cs >>= \(a,cs') -> parse (f a) cs' instance MonadPlus Parser where mzero = Parser $ \_ -> mzero p `mplus` q = Parser $ \cs -> parse p cs `mplus` parse q cs ---------------------------------------------------------------- item :: Parser Char item = Parser f where f [] = mzero f (c:cs) = return (c,cs) ---------------------------------------------------------------- satisfy :: (Char -> Bool) -> Parser Char satisfy f = item >>= check where check c | f c = return c | otherwise = mzero char :: Char -> Parser Char char c = satisfy (c ==) ---------------------------------------------------------------- string :: String -> Parser String string [] = return [] string (c:cs) = (:) <$> char c <*> string cs