【发布时间】:2015-05-23 15:53:42
【问题描述】:
Continuation-passing style 如何通过 Python 实现?
(我认为这是正确的术语)
我的代码开始变得乱七八糟,我有map、filter 和lambdas 链,如下所示:
(lambda a,b: (lambda c:(lambda d: d*d)(c-b))(a*b))(5,6)
“管道表达式”可以在多种语言中找到,例如:
F# 解决方案(例如:|>)
let complexFunction =
2 (* 2 *)
|> ( fun x -> x + 5) (* 2 + 5 = 7 *)
|> ( fun x -> x * x) (* 7 * 7 = 49 *)
|> ( fun x -> x.ToString() ) (* 49.ToString = "49" *)
Haskell 解决方案(例如:do、pipes)
main = do
hSetBuffering stdout NoBuffering
str <- runEffect $
("End of input!" <$ P.stdinLn) >-> ("Broken pipe!" <$ P.stdoutLn)
hPutStrLn stderr str
JavaScript(例如:async.js):
async.waterfall([
function(callback) {
callback(null, 'one', 'two');
},
function(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
不过,我知道最后一种策略更适用于异步函数响应解析(请参阅:callback hell)。
如何在单个 Python 表达式/行中呈现我的所有处理阶段?
【问题讨论】:
-
@myaut:Async.js 只是一个示例,也许我会将其替换为 F# 和 Haskell 示例以更清晰。
-
@AT 执行 Python 示例不会获得太多可读性,因为第二个 lambda 的定义不能移出最外层 lambda 的定义,因为它依赖于
b。 -
难道你不能通过实现简单的fluent interface来解决问题吗?
-
我会说 - 不要尝试在 python 中编写 haskell,它不会很好,如果你陈述你想要解决的问题,我相信有人能够帮助你
标签: python pipeline continuations async.js delimited-continuations