haskell无法构造无限类型

时间:2013-09-26 22:40:27

标签: loops haskell where

我认为以下代码应该有效:

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)

为什么不编译?

1 个答案:

答案 0 :(得分: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_it应用于sum,然后将其添加到i i(即i应用于本身),然后减1。

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