9

从哪里可以获得完整的 Haskell 代码编写缩进规则集?

与我的以下问题类似的过去 SO 问题导致我提出上述问题。错误消息背后的原因是什么:parse error on input 'something'

我得到的错误信息:

baby.hs:103:2:输入“myList”时解析错误(此行错误)

我正在尝试编译的代码:

myList = ["aeroplane", "Aeroplane", "AeRoPlAne", "helicopter", "HELICOPTER", "Zebra"]
quicksort :: (Ord a) => [a] -> [a]  
quicksort [] = []  
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]  
biggerSorted = quicksort [a | a <- xs, a > x]  
in smallerSorted ++ [x] ++ biggerSorted

优化编辑:

我将问题中的代码转移到新的 .hs 文件并尝试编译它。仍然存在类似的错误消息。详情如下:

错误
quickSort.hs:5:62:输入“=”时解析错误失败,加载模块:无。(0.02 秒,0 字节)

代码快速排序 :: (Ord a) => [a] -> [a]
quicksort [] = [] quicksort (x:xs) = let smallSorted = quicksort [a | a <- xs, a <= x]
大排序 = 快速排序 [a | a <- xs, a > x]
in smallSorted ++ [x] ++ largeSorted
myList = ["aeroplane", "Aeroplane", "AeRoPlAne", "helicopter", "HELICOPTER", "Zebra", "America"]

4

2 回答 2

12

至少对于标准 Haskell(没有语言扩展),布局规则在 Haskell 2010 报告的第 10.3 节中进行了解释。

根据您的口味,该报告可能有点正式。Haskell 的各种教程和教科书对布局规则有一些更非正式的解释,例如Haskell Wikibook。

在您的特定情况下,错误消息指向第 103 行,但您只粘贴了几行。我可以看到至少 let-in 结构的缩进被破坏了。您应该编写如下内容:

xs = ["aeroplane", "Aeroplane", "AeRoPlAne", "helicopter", "HELICOPTER", "Zebra"]
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = let smallerSorted = quicksort [a | a <- xs, a <= x]
                       biggerSorted = quicksort [a | a <- xs, a > x]
                   in smallerSorted ++ [x] ++ biggerSorted
于 2012-06-29T12:51:24.573 回答
3

如果我理解正确,避免此问题的最简单方法是编写单个dolet如下所示:

fName = do
  expression1 = ...
  exp2 ...

fName param = let
  exp1 = ...
  exp2 = ...
  exp3 = ...
  in ...        -- can be indented more if you want

这里的要点是,exp1在每个新行中,第一个缩进很容易发现和维护。




这是我学习表中的复制/粘贴。这不是很多,但可能会帮助某人。如果有人发现任何错误/错误,请纠正我。

制表符或空格表示 BLOCK,例如 {com1; com2} 在 C++ 中

越位规则:在源文件的开头,第一个顶级声明或定义可以从任何列开始。每个后续的顶级声明必须具有相同的缩进!

LET IN, WHERE 记住它看到的下一个标记的缩进。如果空行或缩进更靠右,则继续上一行。如果缩进相同,这是同一块中新项目的开始。

win tab 4 spc, unix tab 8 个空格 用空格代替 tab !!!

line1... 
   continue line 1 -- as long it doesn't start at same indent as line1
   3spaces would indicate block with line 1!
   line4 same block
   same indent is same line1 block
   all indents for BLOCK must be same.

line8...    -- is new block and end of line1 block
   positon of first column in block is start

line 1
 cont line1
  cont line 1
   cont line 1
    block1  -- would be cont line 1
    block1  --  if not for this block1 at same indent


Bad way:
do
  action0
  if condition
  then action1
  else action2
  action3

Good way:
do
  action0
  if condition
    then action1
    else action2
  action3
于 2012-06-30T07:59:51.233 回答