Loops haskell无法构造无限类型
我认为以下代码应该可以工作:Loops haskell无法构造无限类型,loops,haskell,where,Loops,Haskell,Where,我认为以下代码应该可以工作: 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
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)
:3:15:错误:
•发生检查:无法构造无限类型:
t2~(t0->t2)->t2
预期类型:t2->t2
实际类型:t2->(t0->t2)->t2
•在“总结”方程式中:
总结
=循环0 x
哪里
循环求和
|i>0=循环求和+i-1
|i==0=和
•相关绑定包括
循环:t2->t2(绑定时间:3:15)
为什么不编译它?您需要在递归调用
循环的参数周围加上括号:
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\u it
到sum
,然后将其添加到i
(即i
应用到自身),然后减去1
这是因为函数应用程序在Haskell中具有最高优先级,所以函数应用程序绑定比算术更紧密
((loop_it sum)+(i i))-1