Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 924
Skyfe Avatar asked Dec 02 '25 21:12

Skyfe


1 Answers

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 i i (i.e. 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.

like image 56
Gabriella Gonzalez Avatar answered Dec 05 '25 19:12

Gabriella Gonzalez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!