如何在Haskell中编写与Int和Char一起使用的case块

gol*_*iii -1 int haskell char

我正在处理一些Haskell代码,偶然发现了一个问题。基本上,我正在编写一个代码块的情况,以检查由用户提供的输入,该输入检查用户输入是否为任何可接受的字符以及整数

我尝试在第一个case块之后编写另一个case块,但无法解决。我试图编写一个if-else块,以检查在case块之前是否输入为int,但这也失败了

这是从函数中间获取的代码块:

if player == 1 then
           do newline
              putStr "Nim: r a / ? / q > "
              inp <- getLine
              let inputs = words inp
                  h = head inputs
              case h of
                 "q" -> do
                    play
                 "?" -> do
                    putStrLn "r is the row and a is amount to remove"
                    putStrLn "The person to remove the last piece wins"
                    play board player

                 -- The case below is the one that I can't seem to make work
                 -- Wrote Int -> do now just to make it clear what I'm looking to do 
                 Int -> do
                    let row = (read(inputs !! 0) :: Int)
                    let row = (read(inputs !! 1) :: Int)
                    if valid board row num then
                       play (move board row num) (next player)
                    else
                       do newline
                          putStrLn "ERROR: Invalid move"
                          play board player

Run Code Online (Sandbox Code Playgroud)

预期场景:

Nim: r a / ? / q > q
>> "quits game"

Nim: r a / ? / q > ?
>> r is the row and a is amount to remove
>> etc etc...

Nim: r a / ? / q > 2 2
>> "Perform move 2 2"

Run Code Online (Sandbox Code Playgroud)

前两个方案起作用。我唯一的问题是在case块中集成一种检查输入是否为整数的方法。

任何帮助表示赞赏

lef*_*out 7

输入将始终是字符串。该字符串可以包含整数的十进制表示形式,但不会改变类型。

因此,您要检查的是是否有一个可以解析为整数的字符串。做到这一点的一种好方法是使用readMaybe。这意味着您实际上h不是在检查自己,而是在检查自己(即尝试读取所有输入,检查是否全部成功)。但是我们仍然可以使用同一块,我们只需要引入修改后的表达式即可与模式卫士相匹配。当我们使用它时,让我们完全摆脱它,只需放入case表达式中:readMaybe hmapM readMaybe inputscasehinputs

          case inputs of
             ["q"] -> do
                play
             ["?"] -> do
                putStrLn "r is the row and a is amount to remove"
                putStrLn "The person to remove the last piece wins"
                play board player

             -- The case below is the one that I can't seem to make work
             -- Wrote Int -> do now just to make it clear what I'm looking to do 
             _ | Just [row, num] <- mapM readMaybe inputs
               -> if valid board row num then
                   ...
Run Code Online (Sandbox Code Playgroud)

  • amalloy:不再是了 – Haskell 2010 添加了 PatternGuards,这是您正在考虑的扩展。 (2认同)