[编辑]
这是How to implement a stack-safe chainRec operator for the continuation monad?
的后续问题
给定是chainRec的类型
chainRec :: ChainRec m => ((a -> c, b -> c, a) -> m c, a) -> m b
通常,chainRec与trampoline一起实现,以允许在monad中进行堆栈安全递归.但是,如果我们放下蹦床,我们可以为普通函数实现chainRec的类型,如下所示:
const chainRec = f => x => join(f(chainRec(f), of, x));
接下来,我想将它应用于递归操作:
const map = f => g => x => f(g(x));
const join = f => x => f(x) (x);
const of = x => y => x;
const chainRec = f => x => join(f(chainRec(f), of, x));
const repeat = n => f => x =>
chainRec((loop, done, args) =>
args[0] === 0
? done(args[1])
: loop([args[0] - 1, map(f) (args[1])])) ([n, of(x)]);
const inc = x => of(x + 1);
repeat(10) (inc) (0) (); // error
我认为,由于chainRec的定义中存在连接,因此必须在repeat的实现中涉及映射,因此有两个嵌套的functorial上下文要崩溃.然而它不起作用,我不知道如何解决它.
最佳答案 不知道你的重复函数做了什么,我想你的调用repeat(10)(inc)(0)应该扩展为
map(inc)(
map(inc)(
map(inc)(
map(inc)(
map(inc)(
map(inc)(
map(inc)(
map(inc)(
map(inc)(
map(inc)(
of(0)
)
)
)
)
)
)
)
)
)
)
由于您的公司因某种原因确实返回了一个函数_ => Int而不是普通的Int,这将在函数x上调用x 1,这导致该函数的字符串化(y => x变为“y => x1”),这将在尝试调用时抛出异常.
在修复const inc = x =>之后x 1;,您的重复功能仍然无效.它需要是简单的递归
const id = x => x
// rec :: ((a -> c, b -> c, a) -> c) -> a -> b
// here with c == b, no trampoline
const rec = f => x => f(rec(f), id, x) // a bit like the y combinator
const repeat = n => f => x =>
rec((loop, done, [m, g]) =>
m === 0
? done(g)
: loop([m - 1, map(f)(g)])
)([n, of(x)]);
repeat(10)(inc)(0)() // 10 - works!
根本没有涉及monad!
如果我们想使用chainRec,我们需要引入一些任意monad(这里:函数monad),并且对chainRec的f回调需要返回该monad类型的实例而不仅仅是loop / done:
chainRec :: ChainRec m => ((a -> c, b -> c, a) -> m c, a) -> m b
// ^
我们可以通过简单地包装返回值来实现:
const repeat = n => f => x =>
chainRec((loop, done, [m, g]) =>
of(m === 0
// ^^
? done(g)
: loop([m - 1, map(f)(g)])
)
)([n, of(x)]);
当然现在得到一个m b,即包含在另一个函数中的所有东西:
repeat(10)(inc)(0)()() // 10
// ^^
// repeat(1)(inc)(0) expands to `of(map(inc)(of(0)))
但我怀疑这是你想要的.