,我正在努力理解为什么这是错误的。 GHCi尚未显示其函数类型或引发错误,这使我难以调试。是否有原因:1.为什么不引发任何错误2.什么使此代码不起作用?
:{
let sumCircle [] = error "empty list";
sumCircle [x] = 3.14159*x^2;
sumCircle [x:restOfList] = sumCircle x + sumCircle restOfList
}:
答案 0 :(得分:6)
您的多行输入定界符被交换。您需要:}
才能关闭多行输入,而不是}:
。请记住,冒号(:
)向GHCi发出信号,表明行内容不是Haskell,而是GHCi特定的构造。
我们也可以在GHCi的提示符下看到这一点:
Prelude> :{
Prelude| let sumCircle [] = error "empty list";
Prelude| sumCircle [x] = 3.14159*x^2;
Prelude| sumCircle [x:restOfList] = sumCircle x + sumCircle restOfList
Prelude| }:
Prelude|
请注意,它仍然是Prelude|
,而不是Prelude>
。改为使用:}
时,由于}:
而导致语法错误:
Prelude| :}
<interactive>:5:1: error:
parse error (possibly incorrect indentation or mismatched brackets)
如果我们从一开始就使用正确的定界符,则会导致预期的类型错误:
Prelude> :{
Prelude| let sumCircle [] = error "empty list";
Prelude| sumCircle [x] = 3.14159*x^2;
Prelude| sumCircle [x:restOfList] = sumCircle x + sumCircle restOfList
Prelude| :}
<interactive>:4:56: error:
* Occurs check: cannot construct the infinite type: t ~ [t]
* In the first argument of `sumCircle', namely `restOfList'
In the second argument of `(+)', namely `sumCircle restOfList'
In the expression: sumCircle x + sumCircle restOfList
* Relevant bindings include
restOfList :: [t] (bound at <interactive>:4:18)
x :: t (bound at <interactive>:4:16)
sumCircle :: t -> [t] (bound at <interactive>:2:5)
顺便说一句,您可以使用pi
代替3.1415926…
,并且使用sum
和map
不需要显式递归,但这是为了以后的清理