试图理解haskell中的缩进

时间:2017-12-09 11:25:09

标签: haskell

我正在努力制作解决河内塔的计划。我为锻炼做了一点复杂:

hanoi :: [Int] -> String
hanoi n
    | n > 0     = hanoi' n "1" "2" "3"
                    where hanoi' n a b c
                            | n == 0    = "|"
                            | otherwise = let pre   = hanoi' (n-1) a c b
                                              posle = hanoi' (n-1) b c a
                                              in pre ++ a ++ " ~~> " ++ c ++ posle    
    | otherwise = "Number must be greater than 0!!!"

但我明白了:

hanoi.hs:7:97: parse error on input ‘=’

有人可以向我解释发生了什么事吗?我现在看到我不理解该语言的一个重要部分。

1 个答案:

答案 0 :(得分:3)

所有警卫之后,where必须

hanoi :: [Int] -> String
hanoi n
    | n > 0     = hanoi' n "1" "2" "3"
    | otherwise = "Number must be greater than 0!!!"
  where hanoi' n a b c
         | n == 0    = "|"
         | otherwise = let pre   = hanoi' (n-1) a c b
                           posle = hanoi' (n-1) b c a
                       in pre ++ a ++ " ~~> " ++ c ++ posle

这是stated in 4.4.3,虽然如果你不习惯类似BNF的语法,它会有些隐藏:

decl    →   (funlhs | pat) rhs

funlhs  →   var apat { apat }
    |   pat varop pat
    |   ( funlhs ) apat { apat }

rhs     →   = exp [where decls]
    |   gdrhs [where decls] 

gdrhs   →   guards = exp [gdrhs]

guards  →   | guard1, …, guardn         (n ≥ 1)

guard   →   pat <- infixexp         (pattern guard)
    |   let decls       (local declaration)
    |   infixexp        (boolean guard) 

rhs是重要的标记。它是包含可选where的唯一部分。 guard可能只包含表达式,后面跟着其他警卫。