[英]Haskell if then else parse error on input `else'
if even 2 then 10 else 11 -- works fine
if even 2 then let t = 10 else let s = 11 -- _:27: parse error on input 'else'
if even 2 then 10 else let s = 11 -- _:34 parse error (possibly incorrect indentation or mismatched brackets)
because let's say I want to code something like this with [[p]]: 因为我要说我想用[[p]]编写这样的代码:
[ t | let e = [],
let o = p!!14, r <- [13,12..1],
if even r
then
let o = zipWith (+) (p!!r) (zipWith max e (drop 1 e))
t = o
else
e = zipWith (+) (p!!r) (zipWith max o (drop 1 o))
t = e ]
which at load time reports the error . 在加载时报告错误。 .
。 .
。 _:33: parse error on input `else'
_:33:输入`else'解析错误
You seem to be assigning different values to a binding in different branches in an imperative way. 您似乎正在以命令方式为不同分支中的绑定分配不同的值。 This doesn't work in Haskell, you must instead of the conditional inside the assignment of the binding like so:
这在Haskell中不起作用,你必须代替绑定赋值内的条件,如下所示:
[ t | let e = [],
let o = p!!14,
r <- [13,12..1],
let t = if even r
then zipWith (+) (p!!r) (zipWith max e (drop 1 e))
else zipWith (+) (p!!r) (zipWith max o (drop 1 o))
]
Note that the if has to line up. 请注意,if必须排队。 It must either start on the same line as the
=
or it must be at the same or greater indentation level as the =
on the following line. 它必须在与
=
相同的行上开始,或者必须与下一行中的=
相同或更大的缩进级别。
Another thing I notice is that e
will always be []
and I imagine this wasn't the intention. 我注意到的另一件事是
e
将永远是[]
而我想象这不是意图。
The then
and the else
part in an if expression should return the same type in Haskell. if表达式中的
then
和else
部分应该在Haskell中返回相同的类型。
It's syntax is like this: 它的语法是这样的:
if <condition> then <true-value> else <false-value>\
In your example, there is no point of using let
unless you are planning to use that variable in the if conditional itself. 在您的示例中,除非您计划在if条件本身中使用该变量,否则无法使用
let
。
LYAH book nicely points out the difference of If conditional as compared to imperative languages: LYAH书很好地指出了与命令式语言相比有条件的区别:
The difference between Haskell's if statement and if statements in imperative languages is that the else part is mandatory in Haskell.
Haskell的if语句和命令式语言中的if语句之间的区别在于,Haskell中的else部分是必需的。 In imperative languages you can just skip a couple of steps if the condition isn't satisfied but in Haskell every expression and function must return something.
在命令式语言中,如果条件不满足,您可以跳过几个步骤,但在Haskell中,每个表达式和函数都必须返回一些内容。
then
let o = zipWith (+) (p!!r) (zipWith max e (drop 1 e))
t = o
"in" keyword must be after "let" expression “in”关键字必须在“let”表达式之后
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.