Haskell 在一种条件下定义多个变量?

标签 haskell if-statement where-clause let

好吧,我可能做错了,但这让我抓狂。我找不到任何东西可以做我想做的事情

采用这个伪代码

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/

相关文章:

Haskell 从用户读取 n 个数字并返回它们的总和

haskell - haskell中多个类型变量的顺序规则是什么?

php if/else 简写失败

R 循环 : Adding a column to a table if does not already exist

mysql - 在表中,如何通过保留其他列的引用来选择一列的不同值?

haskell - 通过仆人在运行时更改网络根目录(或路径前缀)?

haskell - seq 不强制评估

javascript - 如何在 javascript 中的 if 子句中区分输入值或 td 文本内容

mysql左连接和搜索

Mysql WHERE IN 映射