E4108

E4108#

循环预计会产生一个值,请添加 else 分支。

当编译器根据 for 循环的上下文(例如函数的返回类型)推断出 for 循环应该产生一个非 Unit 值,但循环缺少一个 else 分支来提供该值时,就会发生此错误。

In MoonBit, when a for-loop is used in a context where a value is expected (for example, when the function returns a non-Unit type), the loop must have an else branch that specifies what value to return when the loop completes normally. This is because:

  1. 循环体本身不能产生值(与 loop 表达式不同)

  2. Without an else branch, there’s no way to determine what value should be returned when the loop finishes without breaking

这通常发生在两种情况下:

  • 当 for 循环是返回非 Unit 类型的函数中的最后一个表达式时

  • 当 for 循环的结果被赋值给一个变量或用于一个需要非 Unit 值的表达式时

错误示例#

pub fn f(x: Int) -> Int {
  for i = 0, acc = 0; i < x; i = i + 1, acc = acc + i {
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: The for loop is
//                                                      not expected to yield a
//                                                      value, please add an
//                                                      `else` branch.
  }
}

pub fn g(x: Int) -> Int {
  for i in 0..=x {
  }
}

建议#

To fix this error, you can:

  • add an else branch to the for-loop:

pub fn f(x: Int) -> Int {
  for i = 0, acc = 0; i < x; i = i + 1, acc = acc + i {
  } else {
    acc
  }
}
  • change the function’s return type to Unit if you don’t need to return a value from the loop:

pub fn g(x: Int) -> Unit {
  for i in 0..=x {
  }
}