You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)

说明:

  1. 给内层的if链补充了else True,确保每个if都有完整的then/else结构,让整个分支的表达式合法。
  2. 调整where的缩进,使其和最外层if的缩进一致,这样编译器能正确识别where块属于整个函数体。

内容的提问来源于stack exchange,提问作者Rando McRandom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:01:22