Haskell if then else 解析输入`else'时出错

use*_*181 1 haskell

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)
Run Code Online (Sandbox Code Playgroud)

因为假设我想用 [[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 ]
Run Code Online (Sandbox Code Playgroud)

在加载时报告错误。. . _:33: 输入 `else' 解析错误

Dav*_*vid 5

您似乎以命令式方式为不同分支中的绑定分配不同的值。这在 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))
]
Run Code Online (Sandbox Code Playgroud)

请注意, if 必须排队。它必须与 开始在同一行,=或者必须=与下一行的缩进级别相同或更高。

我注意到的另一件事是e永远如此[],我想这不是意图。