简体   繁体   中英

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 :

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.

This happens because function application has highest precedence in Haskell, so function application binds more tightly than arithmetic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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