3

考虑以下一段可操作的 Haskell 代码:

代码 A

describeList :: [a] -> String
describeList xs = "The list is " ++ what xs
    where what [] = "empty."
          what [x] = "a singleton list."
          what xs = "a longer list."

这是取自Syntax in Functions的片段。现在假设我们从下面这段严重缩进且不可操作的 Haskell 代码开始:

代码 B

describeList :: [a] -> String
describeList xs = "The list is " ++ what xs
where what [] = "empty."
what [x] = "a singleton list."
what xs = "a longer list."

那么是否有任何工具可以将缩进严重的代码(代码 B)并正确缩进它以产生可操作的代码(代码 A)?

4

1 回答 1

6

这几乎是不可能做到的(我写这个作为回应,因为我自己一直在寻找可以做到这一点的工具)因为未缩进的 Haskell 代码可能非常模棱两可。

考虑代码:

describeList :: [a] -> String
describeList xs = "The list is " ++ what xs
  where what [] = "empty."
        what [x] = "a singleton list."
        what xs = "a longer list."

让我们也考虑一些替代的,也是有效的解释:

 -- top-level function "what" without type signature
describeList :: [a] -> String
describeList xs = "The list is " ++ what xs
  where what [] = "empty."
what [x] = "a singleton list."
what xs = "a longer list."

-- same as above
describeList :: [a] -> String
describeList xs = "The list is " ++ what xs
  where what [] = "empty."
        what [x] = "a singleton list."
what xs = "a longer list."

-- There might be a `data String a b`, so `String describeList xs` is
-- a type. The clause then becomes a guarded pattern match (similar to 
-- `let bar :: Int = read "1"`) with scoped type variables. The `where`
-- clause is still syntactically valid. The whole thing might not compile,
-- but a syntax tool can't know that.
describeList :: [a] -> String
                       describeList xs = "The list is " ++ what xs
  where what [] = "empty."
        what [x] = "a singleton list."
what xs = "a longer list."
于 2012-08-18T11:43:40.387 回答