0

With functions we can abstract from any type. Here is the Option type as an example:

const Some = x => y =>
  k => k(x);

const None = y =>
  k => y;

const sqr = n => n * n;

const run = f => t => t(f);

const x = Some(5) (0),
  y = None(0);

run(sqr) (x); // 25
run(sqr) (y); // 0

Now I want to encode a deferred type to obtain a lazy effect in Javascript. But I don't know the right approach and if such an endeavor even makes sense with Church Encoding. Here is my first shot:

const Deferred = thunk =>
  k => k(thunk());

const inc = n => n + 1;

const sqr = n => n * n;

const run = f => t => t(f);

const x = Deferred(() => inc(4));

run(sqr) (x); // 25

I am totally in the dark here. Does this approach lead to anything meaningful?

  • `None(0)` looks wrong. I would rather expect something like `run(sqr)(None)(0)`/`run(sqr)(Some(5))(0)` or even `run(sqr)(0)(…)`. – Bergi Nov 24 '18 at 19:04
  • "*if such an endeavor even makes sense with Church Encoding*" - I don't think so. your deferred type for lazy evaluation is something like the continuation monad. It doesn't need any encoding since there is only a single case. – Bergi Nov 24 '18 at 19:07
  • @Bergi Yes, `None(0)` is wrong, instead `run(sqr) (0) (Some(5))` as you stated. –  Nov 24 '18 at 19:50
  • 1
    @Bergi I think this was the missing link. Church (and Scott, respectively) require different cases (constructors) to perform their `fold`/`uncons` operation. `Deferred` is just a function in continuation passing style. –  Nov 24 '18 at 20:07
  • Glad you agree - I'll post it as an answer – Bergi Nov 24 '18 at 20:16

1 Answers1

0

Church encoding (and more precisely, Scott encoding) provide a way to encode branching in a data type with different cases (e.g. instance constructors). Your Deferred type however is a (newtype) wrapper over a function that takes a continuation, there are no multiple cases to be encoded. I don't think you can apply the concept here.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375