代码之家  ›  专栏  ›  技术社区  ›  Drakosha

haskell中关于if-then-else缩进的奇怪错误

  •  7
  • Drakosha  · 技术社区  · 15 年前

    我有以下代码:

    foo :: Int -> [String] -> [(FilePath, Integer)] -> IO Int
    foo _ [] _ = return 4
    foo _ _ [] = return 5
    foo n nameREs pretendentFilesWithSizes = do
      result <- (bar n (head nameREs) pretendentFilesWithSizes)
      if result == 0
      then return 0 --  <========================================== here is the error
      else foo n (tail nameREs) pretendentFilesWithSizes
    

    我在上面的评论行中得到一个错误,错误是:

    aaa.hs:56:2:
        parse error (possibly incorrect indentation)
    

    我在使用emacs,没有空格,我不明白我做错了什么。

    2 回复  |  直到 15 年前
        1
  •  8
  •   YasirA    15 年前

    缩进 then else Conditionals and do -notation

        2
  •  11
  •   Travis Brown    15 年前

    这一点在 if do “部分 Wikibooks article 关于哈斯克尔压痕。

    -脱糖者 then else 行看起来像新语句:

    do { first thing
       ; if condition
       ; then foo
       ; else bar
       ; third thing }
    

    其他的 线路能解决问题。

    更新: beginner ,我还将注意到,在Haskell中,以下内容通常被认为更为惯用:

    foo :: Int -> [String] -> [(FilePath, Integer)] -> IO Int
    foo _ [] _ = return 4
    foo _ _ [] = return 5
    foo n (r:rs) filesWithSizes = bar n r filesWithSizes >>= checkZero
      where
        checkZero :: Int -> IO Int
        checkZero 0 = return 0
        checkZero _ = foo n rs filesWithSizes
    

    这和你的工作完全一样 foo ,但它避免了 head tail 以及 if-then-else 控制结构。非正式地说 >>= bar... 从它的 IO 包装和运行它 checkZero ,返回结果”。