【问题标题】:Multiline if statement Haskell多行 if 语句 Haskell
【发布时间】:2014-12-15 15:31:47
【问题描述】:

我正在用 Haskell 写一个简单的程序,功能如下:

tryMove board player die = do
  let moves = getMoves board player die
  putStrLn ("Possible columns to move: " ++ (show $ moves))

  if not $ null moves then
    let col = getOkInput $ moves
    putStrLn " "
    return $ step board (getMarker player) col firstDie
  else
    putStrLn ("No possible move using "++(show die)++"!")
    return board

它需要一个棋盘,如果玩家可以根据掷骰子移动,则返回新棋盘,否则返回旧棋盘。

但是,haskell 不允许我在 if 语句中使用多行。是否可以使用某种限制器,以便我可以在 if 中使用 let 之类的东西?

【问题讨论】:

  • 样式:"Possible columns to move: " ++ (show $ moves) 可以简化为"Possible columns to move: " ++ show moves。当右边有一个变量时不要使用$:它是多余的。
  • @chi:谢谢!在我发布之前应该使用 hlint ;)

标签: haskell if-statement


【解决方案1】:

您需要在每个 then/else 分支上重复 do 关键字。

whatever = do
  step1
  step2
  if foo
    then do
      thing1
      thing2
      thing3
    else do
      thing5
      thing6
      thing7
      thing8

【讨论】:

  • 您应该添加需要这样做的原因。
  • @bheklilr AFAIK,“因为语言规范是这样说的”,所以需要它。
  • 我想说这更多是因为if-then-else 的每个子句都必须是一个有效的结构(带有范围),而thing1; thing2; thing3 不是一个有效的结构,但@987654327 @是。
  • 或者,您可以说它必须是if <expr> then <expr> else <expr>。 OP 的格式不起作用,因为没有do,连续三个单子表达式不会形成有效的表达式。
猜你喜欢
  • 1970-01-01
  • 2012-01-08
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多