Cont monad defined in Frege

18 views
Skip to first unread message

zhou...@163.com

unread,
Nov 22, 2017, 9:07:07 PM11/22/17
to Frege Programming Language
No big deal, only recording my progress striving to understand monad and monad transformer with this tutorial https://en.wikibooks.org/wiki/Haskell/Continuation_passing_style and this https://wiki.haskell.org/All_about_monads#The_Continuation_monad


data Cont r a = Cont { runCont :: ((a -> r) -> r)}

instance Monad (Cont r) where
  pure x = cont ($ x)
  s >>= f = cont $ \c -> runCont s $ \x -> runCont (f x) c

cont :: ((a -> r) -> r) -> Cont r a
cont f = Cont { runCont = f}

runCont :: Cont r a -> (a -> r) -> r
runCont c = Cont.runCont c

callCC f = cont $ \h -> runCont (f (\a -> cont $ \_ -> h a)) h

fun :: Int -> String
fun n = (`runCont` id) $ do
   str <- callCC $ \exit1 -> do
     when (n < 10) (exit1 (show n))
     let ns = map digitToInt (unpacked (show (n `div` 2)))
     n' <- callCC $ \exit2 -> do
       when ((length ns) < 3) (exit2 (length ns))
       when ((length ns) < 5) (exit2 n)
       when ((length ns) < 7) $ do
         let ns` = map intToDigit (reverse ns)
         exit1 $ packed $ (dropWhile (== '0') ns')
       return $ sum ns
     return $ "(ns = " ++ (show ns) ++ ") " ++ (show n')
   return $ "Answer: " ++ str


zhou...@163.com

unread,
Nov 22, 2017, 9:10:05 PM11/22/17
to Frege Programming Language
The code is working on my 3.24.100 Frege Repl, and I am trying to reinvent ContT monad transformer in Frege now, hope I can learn more about Haskell

在 2017年11月23日星期四 UTC+8上午10:07:07,zhou...@163.com写道:

Dierk König

unread,
Nov 23, 2017, 1:44:02 AM11/23/17
to frege-program...@googlegroups.com
Cool! Bring it on!

Dierk

sent from:mobile 
--
You received this message because you are subscribed to the Google Groups "Frege Programming Language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to frege-programming-l...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages