haskell - Trying to exercise with the Cont monad. Syntax issue -


after study ([1], [2], [3] among others) trying make work of continuation monad attempting examples on own.

the second answer [1] suggests express factorial using continuations. solution following:

cont ($ (fact 0)) = return 1 cont ($ (fact n)) = cont ($ (fact (n-1))) >>= (\x -> cont ($ (n*x))) 

i've done simulations on paper , solution should correct.

however i unable have digested ghc. of course renamed fact function, still no joy.

my latest attempt https://gist.github.com/muzietto/595bef1815ddf375129d , gives parse error in pattern \c -> .....

can suggest running implementation these definitions?

[1] how , why haskell cont monad work?

[2] http://hackage.haskell.org/package/mtl-1.1.0.2/docs/control-monad-cont.html

[3] https://wiki.haskell.org/monadcont_under_the_hood

first, can not define function in way posted same reason can not implement predecessor function follows:

1 + (predecessor x) = x 

functions can defined through equations of form

f pattern1 .. patternk = expression 

note f must found @ top-level.

for factorial function using continuation monad, can simplify attempt follows:

fact :: int -> cont r int -- own code: -- cont ($ (fact 0)) = return 1 fact 0 = return 1 -- cont ($ (fact n)) = cont ($ (fact (n-1))) >>= (\x -> cont ($ (n*x))) fact n = fact (n-1) >>= \x -> return (n*x)  -- "real" factorial function, without monads factorial :: int -> int factorial n = runcont (fact n) id 

note return (n*x) above indeed cont ($ (n*x)), think it's more readable in former way, because not break abstraction. indeed, work in any monad once written above.

alternatively, use do notation.

fact :: int -> cont r int fact 0 = return 1 fact n =    x <- fact (n-1)    return (n*x) 

or use functor operator:

fact :: int -> cont r int fact 0 = return 1 fact n = (n*) <$> fact (n-1) 

Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -