sapply not in a continuation style, so you need to replace it.
Here's a translation into the style of continuing transmission in Python (another language that doesn't have the right tail calls):
def sum_ways_cps(n_times, k_sum, s_side, ctn): """Compute the number of ways to get the sum k by rolling an s-sided die n times. Then pass the answer to ctn.""" if k_sum < n_times or k_sum > n_times * s_side: return ctn(0) elif n_times == 1: return ctn(1) else: f = lambda j, ctn: sum_ways_cps(n_times - 1, k_sum - j, s_side, ctn) return sum_cps(1, s_side + 1, 0, f, ctn) def sum_cps(j, j_max, total_so_far, f, ctn): """Compute the sum of f(x) for x=j to j_max. Then pass the answer to ctn.""" if j > j_max: return ctn(total_so_far) else: return f(j, lambda result: sum_cps(j + 1, j_max, total_so_far + result, f, ctn)) sum_ways_cps(2, 7, 6, print)
Jason Orendorff Jan 11 '17 at 19:05 2017-01-11 19:05
source share