【问题标题】:if requires an else clauseif 需要 else 子句
【发布时间】:2013-05-07 19:26:20
【问题描述】:

我在一个函数中基本上有以下代码,我想消除doSomethingElse()的重复:

fun a ->
    if a = b then
        let c = expensiveOperation()
        if c = d then
            result
        else
            doSomethingElse()
    else
        doSomethingElse()

我认为我应该能够消除这两个 else 子句。让它返回resultdoSomethingElse()。当我这样做时,来自编译器的错误消息是:“这个表达式应该有类型单元,但这里有 int 类型”

为什么if 表达式需要else 子句?

【问题讨论】:

标签: f# semantics


【解决方案1】:

这相当于你写的,但我想知道你是否还有别的意思。

if a = b && expensiveOperation() = d then result
else doSomethingElse()

【讨论】:

  • 目标是避免expensiveOperation(),我没有考虑布尔表达式的快捷方式。我们只会评估&&if a = b 的右侧,所以我可以按照您的建议进行操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
相关资源
最近更新 更多