On Mon, Dec 8, 2008 at 1:40 PM, 甜瓜 <littlesweetmelon@gmail.com> wrote:
Hi,
I am confused by section 4.6 in Yet Another Haskell Tutorial written
by Hal Daume III.
The auther provides a CPS form of "fold" funtion, but I don't know:
1. How to transform a normal function into CPS function. I need some
hint in writting "cfold".

Normal function(s) return value(s).

CPS functions take the same value and uses/throws it as a parameter/argument to the "extra" argument, the Continuation.

so to transform a function into CPS just
1) make the function take one extra argument, the continuation (the "rest" of the process, next function in chain)
2) instead of returning a value, apply the continuation to the value (call the continuation with the result you would normally return)

Example (taken from http://en.wikibooks.org/wiki/Haskell/CPS , check it out)

square :: Int -> Int
square x = x ^ 2

main = do
  let x = square 4
  print x

in CPS :

squareCPS :: Int -> (Int -> a) -> a
squareCPS x k = k (x ^ 2)

main = squareCPS 4 print

which shows that here, the print function is the continuation for the square function.
instead of returning the value (16, or 4*4 here), the CPS variant feeds the value to the continuation (print here)

hope it helps.