Haskell CPS: How to implement map and filter functions using Cont monad? -


i've been trying learn cps, seems didn't head around it, implement basic filter , map using cont monad?

to this, let's first start without monad since cps isn't dependent on it.

cpsmap :: (a -> b) -> [a] -> ([b] -> r) -> r cpsmap f (a:as) c = cpsmap f (c.(f a:)) cpsmap  _ []    c = c []  map' f xs = cpsmap f xs id 

and cont monad trivial

contmap :: (a -> b) -> [a] ->  cont r [b] contmap f (a:as) = contmap f >>= return . (f :) contmap _ [] = return []  map'' f xs = runcont (contmap f xs) id 

the difference here don't have touch continuations ourselves, return pipes value us.

to visualize let's trace map'' (+1) [1..3]

as      | c [1,2,3] | id [2,3]   | id . (2 :) [3]     | id . (2 :) . (3 :) []      | id . (2 :) . (3 :) . (4 :) id . (2 :) . (3 :) . (4 :) $ [] [2, 3, 4] 

notice cont wrap ([b] -> r) -> r part of our code under newtype. can think of cont as

newtype cont r = cont ((a -> r) -> r) 

i'll leave implementing filter :)


Comments

Popular posts from this blog

user interface - Python attempting to create a simple gui, getting "AttributeError: 'MainMenu' object has no attribute 'intro_screen'" -

jquery - Common JavaScript snippet to share files on Google Drive, Dropbox, Box.net or SkyDrive -

Android Gson.fromJson error -