[英]haskell cannot construct the infinite type
我认为以下代码应该工作:
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)
为什么不编译?
你需要围绕递归调用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
,然后将其添加到ii
(即i
应用于自身),然后减去1。
这是因为函数应用程序在Haskell中具有最高优先级,因此函数应用程序比算术绑定更紧密。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.