好吧,我可能做错了,但这让我抓狂。我找不到任何东西可以做我想做的事情
采用这个伪代码
my_function left right
= another_function new_left new_right (fourth_function new_left new_right)
where new_left = if some_condition then left else third_function left
new_right = if some_condition then third_function right else right
如何避免重新检查 some_condition?我并不是在谈论将 some_condition
保存为 where
构造中的另一个变量。如果我将 let
放入 if
中,则将 复制到 another_function new_left new_right
中。
用命令式语言我可以做类似的事情
int new_left;
int new_right;
if (condition) {
new_left = left;
new_right = third_function(right);
} else {
new_left = third_function(left);
new_right = right;
}
return another_function(new_left, new_right, fourth_function(new_left, new_right));
我知道在函数式语言中,你不应该考虑按顺序做事,而是考虑作为表达式的组合,所以我只是在寻找一种方法来编写原始伪代码,使其保持干燥。这似乎是一个简单且相对常见的案例。
编辑
抱歉造成困惑。我无法内联 third_function left/right
因为我需要使用它的值两次(更新的伪代码)。并且 fourth_function
无法移动到 another_function
最佳答案
怎么样
my_function left right | somecondition =
another_function left (third_function right)
| otherwise =
another_function (third_function left) right
经过新的编辑
my_function left right = ...
where (new_left, new_right) | somecondition = (left, third_function right)
| otherwise = (third_function left, right)
关于Haskell 在一种条件下定义多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102719/