tags:

views:

91

answers:

2

here is a function multiplies the elements in a list using CPS style

mlist xx k = aux xx k
  where aux [] nk = nk 1
    aux (0:xs) nk = k 0
    aux (x:xs) nk = aux xs $ \v -> mul x v nk

what if I change the 'k' to 'nk' in the expression aux (0:xs) nk = k 0, whats the difference between the two ?

+3  A: 

k is always the original continuation passed to mlist whereas for the list [1, 0] nk in that case will be \v -> mul 1 v k (from third case of aux).

If we assume mul is defined as mul x y k = k $ x*y, this doesn't make a practical difference since y will always be 0. But the actual method of arriving at that result is different (barring possible optimizations by the compiler).

Chuck
cool! if the list is longer, we may have optimizations.
baboonWorksFine
IME, using k instead of passing a new continuation often allows for significant compiler optimizations. I have not yet seen a case where using 'k' isn't at least as efficient as 'nk', and it's often measurably faster.
John
+1  A: 

The difference is that the original definition "short circuits" any built-up multiplications passed by tail call applications, while the changed expression only short-circuits testing the values - it keeps the built-up "version" of the continuation function.

BMeph