[Haskell-beginners] [haskell] About CPS form funtions
666wman at gmail.com
Mon Dec 8 10:38:01 EST 2008
On Mon, Dec 8, 2008 at 1:40 PM, 甜瓜 <littlesweetmelon at gmail.com> wrote:
> 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
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
instead of returning the value (16, or 4*4 here), the CPS variant feeds the
value to the continuation (print here)
hope it helps.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners