Continuation ã¢ãã
ç解ããã®ã«ãããè¦å´ããã®ã§ã¡ã¢ã
ã¾ããå®ç¾©ã¯ãããªæãã
instance Monad (Cont r) where return a = Cont $ \k -> k a -- i.e. return a = \k -> k a (Cont c) >>= f = Cont $ \k -> c (\a -> runCont (f a) k) -- i.e. c >>= f = \k -> c (\a -> f a k)http://www.sampou.org/haskell/a-a-monads/html/contmonad.html
runCont
runContã®ä¸èº«ãæ¸ãã¦ãªããã以ä¸ã®ãããªå®ç¾©ã ã¨æãããã
第1å¼æ°ã«Contã¢ãããã¨ããä¸èº«ã®cãåãåºããkã«é©ç¨ããã
runCont (Cont c) k = c k
bind
èªåã¨ãã¦ã¯ã>>=ã®ä¸èº«ã¯ã以ä¸ã®ããã«2ã«æã«runContã使ã£ãå¼ã®æ¹ãããããããã¨æãã
ãªãããã¨ã®å®ç¾©ã§ã®(Cont c)ãccã«å¯¾å¿ããã
cc >>= f = Cont $ \k -> runCont cc (\a -> runCont (f a) k)
ç¶ç¶æ¸¡ãâã¢ãã
以ä¸ãè¸ã¾ãã¦æ®éã«æ¸ããç¶ç¶æ¸¡ãçã®éä¹ããã¢ããçã®éä¹ãå°ãã¦ã¿ãã
fact 0 k = k 1 fact n k = fact (n - 1) (\a -> k $ n * a) main = fact 4 print
kãå¼ã³åºãã¦ããé¨åã(\k -> k ...)ã«å¤å½¢ããã
fact 0 = \k -> k 1 fact n = \k -> fact (n - 1) (\a -> (\k -> k $ n * a) k) main = fact 4 print
(\k -> ...)ããContã¢ãã(Cont $ \k-> ...)ã«ããã
ããã«ãããã¦ãContã¢ããã«å¼æ°ãé©ç¨ãã¦ããã¨ããã¯runContãä»ããããã«ããã
fact 0 = Cont $ \k -> k 1 fact n = Cont $ \k -> runCont (fact $ n - 1) (\a -> runCont (Cont $ \k -> k $ n * a) k) main = runCont (fact 4) print
(Cont $ \k -> k ...) ã (return ...) ã«ç½®ãæãã
fact 0 = return 1 fact n = Cont $ \k -> runCont (fact $ n - 1) (\a -> runCont (return $ n * a) k) main = runCont (fact 4) print
(fact $ n - 1) ã ccã(return $ n * a) ã (f a) ã«å¯¾å¿ããã®ã§ã>>=ã«ç½®ãæããã
ãªããf a = x ã®ã¨ããf = \a->x
fact 0 = return 1 fact n = (fact $ n - 1) >>= (\a -> return $ n * a) main = runCont (fact 4) print
ããã«doè¨æ³ã«å¤å½¢ãã¦å®äºã
import Control.Monad.Cont fact 0 = return 1 fact n = do a <- fact $ n - 1 return $ n * a main = runCont (fact 4) print