r/functionalprogramming • • Jun 29 '20

Question ELI5: what is delimited continuation?

26 Upvotes

7 comments sorted by

2

u/reifyK Jun 30 '20 edited Jun 30 '20

I think you just cannot talk about a topic as abstract as delimited continuations with a kid. Anyway, delimited continuations mean you can compose them, because a continuation doesn't represent the rest of your program anymore, but the rest of your subprogram or task. There are two different pairs of combinators you can use to obtain DC. In my Javascript example I use shift/reset. With DC you control the flow of your program as cannot be achieved by any other language means:

// DELIMITED CONTINUATIONS

const structure = type => cons => {
  const f = (f, args) =>
   ({["run" + type]: f});

  return cons(f);
};

const Cont = structure("Cont")
  (Cont => f => Cont(f));

const runCont = tf => k =>
  tf.runCont(k);

const reset = tf =>
  of(tf.runCont(id));
  
const shift = f =>
  Cont(k => f(k).runCont(id));

const of = x =>
  Cont(k => k(x));
  
const liftM2 = f => tf => tg =>
  Cont(k => runCont(tf) (x => runCont(tg) (y => k(f(x)(y)))));

const id = x => x;

const mulM = liftM2(x => y => x * y);
const addM = liftM2(x => y => x + y);

const main = mulM(of(5))
  (reset
    (addM
      (shift(k => of(3))) // ignore the continuation
        (of(3)))
  ).runCont(id); // 5 * 3

const main2 = mulM(of(5))
  (reset
    (addM
      (shift(k => of(k(3)))) // call the continuation
        (of(3)))
  ).runCont(id); // 5 * (3 + 3)

main; // 15
main2; // 30

run code in repl

0

u/[deleted] Jun 30 '20

[deleted]

1

u/xiaodaireddit Jun 30 '20

How do u control when to come back to it later

1

u/ineffective_topos Jun 30 '20 edited Jun 30 '20

By calling a function. Usually the continuation is a regular function you get back. Sometimes it's a separate datatype, but you always go back to it explicitly and intentionally.

(This generally differs from undelimited continuations, where generally returning a value will pass it to that continuation).