Haskell“哪里"缩进:为什么它必须缩进过去的标识符? [英] Haskell "where" indentation: why must it be indented past identifier?
问题描述
此代码:
import Data.Char (digitToInt)
myInt :: String -> Int
myInt [] = error "bad input: empty string"
myInt (x:xs)
| x == '-' = -1 * myInt xs
| otherwise = foldl convert 0 (x:xs)
where convert acc x
| x `elem` ['0'..'9'] = 10 * acc + digitToInt x
| otherwise = error ("bad input: not an int - " ++ [x])
失败:
前奏> :l safeListFs.hs
[1 of 1] 编译 Main(safeListFs.hs,已解释)
Prelude> :l safeListFs.hs
[1 of 1] Compiling Main ( safeListFs.hs, interpreted )
safeListFs.hs:9:8:解析错误(可能缩进不正确)
失败,加载的模块:无.
safeListFs.hs:9:8: parse error (possibly incorrect indentation)
Failed, modules loaded: none.
但是这个版本:
import Data.Char (digitToInt)
myInt :: String -> Int
myInt [] = error "bad input: empty string"
myInt (x:xs)
| x == '-' = -1 * myInt xs
| otherwise = foldl convert 0 (x:xs)
where convert acc x
| x `elem` ['0'..'9'] = 10 * acc + digitToInt x
| otherwise = error ("bad input: not an int - " ++ [x])
没问题:
前奏> :l safeListFs.hs
[1 of 1] 编译 Main(safeListFs.hs,已解释)
好的,加载的模块:Main.
Prelude> :l safeListFs.hs
[1 of 1] Compiling Main ( safeListFs.hs, interpreted )
Ok, modules loaded: Main.
我不明白为什么最后两个缩进很重要.
I can't figure out why those two last indents matter.
推荐答案
基本上,Haskell 会注意到 where
之后第一个非空格字符出现的列(在这种情况下,c
of convert
) 并将从该列开始的以下几行视为 where
中的新定义.
Basically, Haskell notes the column where the first non-space character after where
appears (in this case, the c
of convert
) and treats following lines beginning in that column as new definitions inside the where
.
继续前一行定义的行(例如您的 |
守卫)必须缩进第一个非空格字符(|
>c 在您的代码中).
A line that continues the definition of the previous line (such as your |
guards) must be indented to the right of the first non-space character (c
in your code).
在 c
左侧缩进的行将在 where
之外(例如,下一个顶级函数的开始).
A line indented to the left of c
would be outside the where
(for example, the start of your next top-level function).
where
之后的第一个字符的列是至关重要的,即使它在一个新行上:
It's the column of the first character following where
that is crucial, even if it's on a new line:
where
convert acc x
| ...
anotherFunction x y
^
这篇关于Haskell“哪里"缩进:为什么它必须缩进过去的标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!