注1:这里的CPS代表“持续通过风格”
我对了解如何挂接到C#异步机制非常感兴趣。基本上,据我了解的C#异步/等待功能,编译器将执行CPS转换,然后将转换后的代码传递给上下文对象,该对象管理各个线程上的任务调度。
您是否认为可以利用该编译器功能来创建功能强大的组合器,同时又保留默认的线程方面?
一个例子就是可以递归和记忆诸如
async MyTask<BigInteger> Fib(int n) // hypothetical example
{
if (n <= 1) return n;
return await Fib(n-1) + await Fib(n-2);
}
Run Code Online (Sandbox Code Playgroud)
我设法做到这一点:
void Fib(int n, Action<BigInteger> Ret, Action<int, Action<BigInteger>> Rec)
{
if (n <= 1) Ret(n);
else Rec(n-1, x => Rec(n-2, y => Ret(x + y)));
}
Run Code Online (Sandbox Code Playgroud)
(不使用异步,非常笨拙...)
或使用monad(While<X> = Either<X, While<X>>)
While<X> Fib(int n) => n <= 1 ?
While.Return((BigInteger) n) :
from x in Fib(n-1)
from y in Fib(n-2) …Run Code Online (Sandbox Code Playgroud) c# stack-overflow combinators continuation-passing async-await