Haskell嵌套if/then语句语法错误:国际象棋合法性函数报错排查
解决Haskell isLegal函数的"parse error on input ‘where’"错误
你的代码存在两个基础语法问题,导致了GHCi的解析错误:
- 嵌套if表达式不完整:处理白兵的分支里,最后一个
else if之后没有对应的else分支。Haskell要求所有if必须同时包含then和else,表达式必须完整,不能只写半截。 - where块缩进错误:
where的缩进必须和函数体的起始表达式(也就是最外层的if)对齐,Haskell靠缩进识别代码块归属,缩进不对会让编译器无法正确解析where的作用范围。
修正后的代码如下:
isLegal :: Int -> Int -> Int -> Int -> Board -> Bool isLegal from_x from_y to_x to_y (MakeBoard board_state) = if (piece_at_origin == Nothing) then False else if (piece_at_origin == Just (Piece Pawn White)) then if not (to_y == from_y + 1) then False else if (x_dist /= 1 && x_dist /= 0) then False else if (x_dist /= 0 && piece_at_destination == Nothing) then False else True -- 补充缺失的else分支,让内层if结构完整 else True where -- 调整缩进,与最外层if对齐 piece_at_origin = board_state from_x from_y piece_at_destination = board_state to_x to_y x_dist = abs (to_x - from_x) y_dist = abs (to_y - from_y)
说明:
- 给内层的if链补充了
else True,确保每个if都有完整的then/else结构,让整个分支的表达式合法。 - 调整
where的缩进,使其和最外层if的缩进一致,这样编译器能正确识别where块属于整个函数体。
内容的提问来源于stack exchange,提问作者Rando McRandom
相关产品推荐
相关产品推荐

