简体   繁体   English

haskell无法构造无限类型

[英]haskell cannot construct the infinite type

I thought the following code should work: 我认为以下代码应该工作:

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

But I'm getting this error: 但是我收到了这个错误:

<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)

Why doesn't this compile? 为什么不编译?

You need parentheses around the arguments of the recursive call to loop_it : 你需要围绕递归调用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

If you don't group it like that, the compiler would implicitly group it like this: 如果你不像那样对它进行分组,编译器会隐式地将它分组如下:

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

... which is probably not what you wanted, since that means: "apply loop_it to sum , then add that to ii (ie i applied to itself), then subtract 1. ...这可能不是你想要的,因为这意味着:“将loop_it应用于sum ,然后将其添加到ii (即i应用于自身),然后减去1。

This happens because function application has highest precedence in Haskell, so function application binds more tightly than arithmetic. 这是因为函数应用程序在Haskell中具有最高优先级,因此函数应用程序比算术绑定更紧密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM