3

所以,我刚开始从Real World Haskell书里自学 Haskell ,在做其中一个练习的过程中,我写了以下代码:

step acc ch | isDigit ch = if res < acc   
                              then error "asInt_fold: \
                                         \result overflowed"
                              else res
                      where res = 10 * acc + (digitToInt ch)
            | otherwise  = error ("asInt_fold: \
                                  \not a digit " ++ (show ch))

当我将其加载到 GHCi 6.6 中时,出现以下错误:

IntParse.hs:12:12: parse error on input `|'
Failed, modules loaded: none.

我几乎可以肯定该错误是由于“where”子句和后续守卫的相互作用造成的;注释掉守卫会消除它,就像用等效的“let”子句替换“where”子句一样。我也很确定我一定是以某种方式破坏了缩进,但我无法弄清楚如何。

提前感谢您的任何提示。

4

2 回答 2

11

where不能放在守卫之间。来自 Haskell Report 中的第4.4.3.1 段函数绑定

于 2009-08-22T15:59:32.957 回答
9

尝试:

step acc ch
    | isDigit ch = if res < acc then error "asInt_fold: result overflowed" else res
    | otherwise  = error ("asInt_fold: not a digit " ++ (show ch))
    where res = 10 * acc + (digitToInt ch)
于 2009-08-22T15:30:54.297 回答