Rae*_*kye 1 haskell if-statement let where-clause
好吧,我可能做错了,但它让我把头发拉了出来.我找不到任何可以做我想要的东西
拿这个伪代码
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
Run Code Online (Sandbox Code Playgroud)
我怎样才能避免重新检查some_condition?而且我不是在讨论some_condition作为where构造中的另一个变量保存.如果我把它lets放进去,if那么复制一下in 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));
Run Code Online (Sandbox Code Playgroud)
我知道在函数式语言中你不应该考虑按顺序做事,而是作为表达式的组合,所以我只是想找一种方法来编写原始的伪代码,这样就干了.这似乎是一个简单而相对常见的案例.
编辑
对困惑感到抱歉.我无法内联,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
Run Code Online (Sandbox Code Playgroud)
随着新的编辑
my_function left right = ...
where (new_left, new_right) | somecondition = (left, third_function right)
| otherwise = (third_function left, right)
Run Code Online (Sandbox Code Playgroud)