Как использовать ContT monad transformer?

#javascript #functional-programming #monads #monad-transformers #continuations

#javascript #функциональное программирование #монады #монады-трансформеры #продолжения

Вопрос:

ContT Monad transformer имеет ту же реализацию, что Cont и monad, но я не могу применить ее ко всем трем Either случаям

  • Right
  • Left из текущего монадического действия
  • Left из предыдущего монадического вычисления

Последний сбой, и все попытки его исправить также не увенчались успехом:

 const record = (type, o) => (
  o[Symbol.toStringTag] = type.name || type,
  o);

const union = type => (tag, o) => (
  o[Symbol.toStringTag] = type,
  o.tag = tag.name || tag,
  o);

const match = (tx, o) => o[tx.tag] (tx);

const Either = union("Either");
const Left = left => Either(Left, {left});
const Right = right => Either(Right, {right});

const eithChain = mx => fm =>
  match(mx, {
    Left: _ => mx,
    Right: ({right: x}) => fm(x)
  });

const ContT = contt => record(ContT, {contt});

const contChainT = mmk => fmm =>
  ContT(c => mmk.contt(x => fmm(x).contt(c)));

const main = foo =>
  contChainT(ContT(k => k(foo))) (mx =>
    eithChain(mx) (x =>
      x === 0
        ? ContT(k => k(Left("ouch!")))
        : ContT(k => k(Right(x * x)))));

main(Right(5)).contt(console.log); // Right(25)
main(Right(0)).contt(console.log); // Left("ouch!")
main(Left("yikes!")).contt(console.log); // Type Error  

Это разочаровывает. Любые подсказки приветствуются!

Ответ №1:

Ваша main функция не проверяет тип.

 const main = foo =>
  contChainT(ContT(k => k(foo))) (mx =>
    eithChain(mx) (x =>
      x === 0
        ? ContT(k => k(Left("ouch!")))
        : ContT(k => k(Right(x * x)))));
  

Во-первых, давайте упростим это. Учитывая, const pureContT = x => ContT(k => k(x)) мы можем переписать main следующим образом.

 const main = foo =>
  contChainT(pureContT(foo)) (mx =>
    eithChain(mx) (x =>
      pureContT(x === 0
        ? Left("ouch!")
        : Right(x * x))));
  

Однако chain(pure(x))(f) это то же f(x) самое, что и (закон левой идентичности). Следовательно, мы можем еще больше упростить.

 const main = mx =>
  eithChain(mx) (x =>
    pureContT(x === 0
      ? Left("ouch!")
      : Right(x * x)));
  

Здесь вы можете увидеть проблему. eithChain Функция имеет следующий тип.

 Either e a -> (a -> Either e b) -> Either e b
  

Однако обратный вызов, заданный to eithChain , возвращает a ContT вместо an Either .


На самом деле я бы сказал, что вы неправильно подходите к этой проблеме.

 ContT r m a = (a -> m r) -> m r

-- Therefore

ContT r (Either e) a = (a -> Either e r) -> Either e r
  

Это не то, что вы хотите. Вместо этого вы должны использовать EitherT transformer.

 EitherT e m a = m (Either e a)

Cont r a = (a -> r) -> r

-- Therefore

EitherT e (Cont r) a = Cont r (Either e a) = (Either e a -> r) -> r
  

Вот что я бы сделал.

 // Left : e -> Either e a
const Left = error => ({ constructor: Left, error });

// Right : a -> Either e a
const Right = value => ({ constructor: Right, value });

// Cont : ((a -> r) -> r) -> Cont r a
const Cont = runCont => ({ constructor: Cont, runCont });

// either : (e -> b) -> (a -> b) -> Either e a -> b
const either = left => right => either => {
    switch (either.constructor) {
    case Left: return left(either.error);
    case Right: return right(either.value);
    }
};

// MonadEitherT : Monad m -> Monad (EitherT e m)
const MonadEitherT = ({ pure, bind }) => ({
    pure: x => pure(Right(x)),
    bind: m => f => bind(m)(either(e => pure(Left(e)))(f))
});

// MonadCont : Monad (Cont r)
const MonadCont = {
    pure: x => Cont(k => k(x)),
    bind: m => f => Cont(k => m.runCont(x => f(x).runCont(k)))
};

// MonadEitherCont : Monad (EitherT e (Cont r))
const MonadEitherCont = MonadEitherT(MonadCont);

// main : Either String Number -> EitherT String (Cont r) Number
const main = either => MonadEitherCont.bind(MonadCont.pure(either))(x =>
    MonadCont.pure(x === 0 ? Left("ouch!") : Right(x * x)));

// show : Either e a -> String
const show = either
    (e => `Left(${JSON.stringify(e)})`)
    (x => `Right(${JSON.stringify(x)})`);

// print : Either e a -> ()
const print = x => console.log(show(x));

main(Right(5)).runCont(print); // Right(25)
main(Right(0)).runCont(print); // Left("ouch!")
main(Left("yikes!")).runCont(print); // Left("yikes!")  

Комментарии:

1. Но зачем мне ContT тогда использовать? Когда я смотрю на стрелку a -> Cont r m b Клейсли ~ a -> (b -> m r) -> m r ~ (b -> m r) -> (a -> m r) это преобразование домена. У вас есть какой-нибудь понятный пример?

2. @scriptum Наиболее распространенным вариантом использования ContT монады было бы сглаживание вложенных монадических вычислений. Следующий пост в блоге Романа Чепляки может вас заинтересовать.

3. @AaditMShah я реализовал версию, основанную на ContT и опубликовал ее в качестве дополнительного ответа.

Ответ №2:

В дополнение к ответу Aadit мне удалось реализовать версию с ContT as transformer. Все, что мне нужно было для управления текущим продолжением, — это стандартная Cont реализация Monad и соответствующая lift :

 const record = (type, o) => (
  o[Symbol.toStringTag] = type.name || type,
  o);

const union = type => (tag, o) => (
  o[Symbol.toStringTag] = type,
  o.tag = tag.name || tag,
  o);

const match = (tx, o) => o[tx.tag] (tx);

const Either = union("Either");
const Left = left => Either(Left, {left});
const Right = right => Either(Right, {right});

const eithChain = mx => fm =>
  match(mx, {
    Left: _ => mx,
    Right: ({right: x}) => fm(x)
  });

const ContT = contt => record(ContT, {contt});

const contChainT = mmk => fmm =>
  ContT(k => mmk.contt(x => fmm(x).contt(k)));

const contLiftT = chain => mmk =>
  ContT(k => chain(mmk) (k));

const log = x => (console.log(x), x);

const main = foo =>
  contChainT(contLiftT(eithChain) (foo)) (x =>
    x === 0
      ? ContT(k => Left("yikes!"))
      : ContT(k => k(x * x)));

const foo = main(Right(5)).contt(x => Right(log(x))); // logs 25
const bar = main(Right(0)).contt(x => Right(log(x)));
const baz = main(Left("ouch!")).contt(x => Right(log(x)));

log(foo); // Right(25)
log(bar); // Left("yikes!")
log(baz); // Left("ouch!")  

Кажется, что ContT / M с произвольной базовой монадой M и T / Cont с произвольным трансформатором T являются коммутативными по своим эффектам. Однако у меня нет математических навыков, чтобы доказать такое утверждение.