[Haskell-beginners] Continuations
Amy de Buitléir
amy at nualeargais.ie
Thu May 28 17:17:11 UTC 2015
Hi Shishir,
Let's first consider a more straightforward version of the function.
λ> let add_cps x y k = k (x+y)
So add_cps is a function of x, y, and k, where k is a function that will be
applied to x+y. Effectively it converts a function (k) of one argument into
a function that takes two arguments. Let's examine the type signature.
Now, k could be any function that takes one variable. Why don't we try
"print"? In the next example, x=3, y=4, and k=print. What do we expect
add_cps to do with those arguments? Well, it should apply the function k
(which is "print") to the argument x+y.
λ> add_cps 3 4 print
7
And that's what it does!
Remember how partial application works? What would happen if we invoke
add_cps, but leave out the final argument? The result is a function. That
function has no name, and we can't print it, but we can look at its type
signature.
λ> :t add_cps 3 4
add_cps 3 4 ∷ Num a ⇒ (a → t) → t
So this unnamed function takes another function of type a → t, and returns a
function of type t. Effectively it converts a function of one argument into
a function that takes two arguments. Let's try that with "print".
λ> let f = add_cps 3 4
λ> f print
7
This leads us to an equivalent way to write add_cps:
λ> let add_cps x y = \k -> k (x+y)
This is identical to the first definition, even though it looks very
different! Can you see why?
More information about the Beginners
mailing list