3

我认为以下代码应该可以工作:

sum_up x = loop_it 0 x
    where loop_it sum i | i > 0     = loop_it sum+i i-1
                        | i == 0    = sum

但我收到了这个错误:

<interactive>:3:15: error:
    • Occurs check: cannot construct the infinite type:
        t2 ~ (t0 -> t2) -> t2
      Expected type: t2 -> t2
        Actual type: t2 -> (t0 -> t2) -> t2
    • In an equation for ‘sum_up’:
          sum_up x
            = loop_it 0 x
            where
                loop_it sum i
                  | i > 0 = loop_it sum + i i - 1
                  | i == 0 = sum
    • Relevant bindings include
        loop_it :: t2 -> t2 (bound at <interactive>:3:15)

为什么不编译?

4

1 回答 1

6

您需要在递归调用的参数周围加上括号loop_it

sum_up x = loop_it 0 x
    where loop_it sum i | i > 0     = loop_it (sum+i) (i-1)  -- <- Here
                        | i == 0    = sum

如果你不这样分组,编译器会像这样隐式分组:

((loop_it sum)+(i i))-1

...这可能不是您想要的,因为这意味着:“应用于loop_itsum然后将其添加到i i(即i应用于自身),然后减去 1。

发生这种情况是因为函数应用程序在 Haskell 中具有最高优先级,因此函数应用程序比算术绑定得更紧密。

于 2013-09-26T22:44:08.243 回答