Sky*_*yfe 3 haskell loops where
我认为以下代码应该工作:
sum_up x = loop_it 0 x
where loop_it sum i | i > 0 = loop_it sum+i i-1
| i == 0 = sum
Run Code Online (Sandbox Code Playgroud)
但是我收到了这个错误:
<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)
Run Code Online (Sandbox Code Playgroud)
为什么不编译?
你需要围绕递归调用的参数括号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
Run Code Online (Sandbox Code Playgroud)
如果你不像那样对它进行分组,编译器会隐式地将它分组如下:
((loop_it sum)+(i i))-1
Run Code Online (Sandbox Code Playgroud)
...这可能不是你想要的,因为这意味着:"应用loop_it到sum,然后添加到i i(即i适用于本身),然后减去1.
这是因为函数应用程序在Haskell中具有最高优先级,因此函数应用程序比算术绑定更紧密.