Sch*_*ron 3 python parsing haskell indentation syntax-error
我刚刚开始学习Haskell并且我简要地阅读了一些缩进规则,在我看来,当涉及到缩进时,Haskell就像Python一样(我可能错了).无论如何,我试着写一个尾递归的斐波纳契函数,我不断收到缩进错误,我不知道在哪里缩进我的代码错了.
错误信息:
F1.hs:6:9: error:
parse error (possibly incorrect indentation or mismatched brackets)
|
6 | |n<=1 = b | ^
Run Code Online (Sandbox Code Playgroud)
码:
fib :: Integer -> Integer
fib n = fib_help n 0 1
where fib_help n a b
|n<=1 = b
|otherwise fib_help (n-1) b (a+b)
Run Code Online (Sandbox Code Playgroud)
注意:我在Notepad ++中编写代码并且我更改了设置,以便在我TAB时创建4个空格而不是制表符(就像我猜的那样)
mel*_*ene 10
不,Haskell缩进不像Python.
Haskell不是关于缩进级别,而是关于使事物与其他事物对齐.
where fib_help n a b
Run Code Online (Sandbox Code Playgroud)
在这个例子中,你有where,而以下的标记不是{.这会激活布局模式(即空格敏感的解析).下一个token(fib_help)设置以下块的开始列:
where fib_help n a b
-- ^
-- | this is "column 0" for the current block
Run Code Online (Sandbox Code Playgroud)
下一行是:
|n<=1 = b
Run Code Online (Sandbox Code Playgroud)
第一个token(|)缩进小于"column 0",隐式关闭块.
您的代码将被解析为您已编写的代码
fib n = fib_help n 0 1
where { fib_help n a b }
|n<=1 = b
|otherwise fib_help (n-1) b (a+b)
Run Code Online (Sandbox Code Playgroud)
这是几个语法错误:where块缺少a =,并且您无法启动新的声明|.
解决方案:缩进应该是where块的一部分而不是第一个令牌之后的所有内容where.例如:
fib n = fib_help n 0 1
where fib_help n a b
|n<=1 = b
|otherwise = fib_help (n-1) b (a+b)
Run Code Online (Sandbox Code Playgroud)
要么:
fib n = fib_help n 0 1
where
fib_help n a b
|n<=1 = b
|otherwise = fib_help (n-1) b (a+b)
Run Code Online (Sandbox Code Playgroud)
要么:
fib n = fib_help n 0 1 where
fib_help n a b
|n<=1 = b
|otherwise = fib_help (n-1) b (a+b)
Run Code Online (Sandbox Code Playgroud)
两件事情:
otherwise=在它之后仍然需要一个标志(otherwise是同义词True):fib :: Integer -> Integer
fib n = fib_help n 0 1
where fib_help n a b
|n<=1 = b
|otherwise = fib_help (n-1) b (a+b)
Run Code Online (Sandbox Code Playgroud)
要说Haskell缩进就像Python那样可能是一种过度概括,仅仅因为语言结构完全不同.更准确的说法是说空白在Haskell和Python中都很重要.