Haskell - 在 do 块中获取用户输入并在 if 语句中使用它

Haskell - Get user input in do block and use it in if statement

这是我的代码

main :: IO ()
main = do
    putStrLn "Pick a number?"
    putStrLn "From 1-5"
    numPick <- getLine
    putStrLn "Thank you for choosing a number."
    if numPick == 1 then
       do createProcess (proc "/usr/bin/ls" [])
    else
       do putStrLn "Do nothing"
    putStrLn "Were done here"

我希望用户选择一个号码,从这个号码中选择的系统进程是 运行。我是 Haskell 的新手,有人知道我做错了什么吗?

我在尝试编译时遇到以下错误。

hlsurl.hs:18:11: error:
    * Couldn't match type `()'
                     with `(Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)'
      Expected type: IO
                       (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
        Actual type: IO ()
    * In a stmt of a 'do' block: putStrLn "Do nothing"
      In the expression: do putStrLn "Do nothing"
      In a stmt of a 'do' block:
        if numPick == 1 then
            do createProcess (proc "/usr/bin/ls" [])
        else
            do putStrLn "Do nothing"
   |
18 |        do putStrLn "Do nothing"
   |           ^^^^^^^^^^^^^^^^^^^^^

createProcess returns 与进程关联的句柄数,而 putStrLn returns 没有 (IO ())。因为 if-else-expression 的两个部分需要是同一类型,所以您需要统一这些函数调用,例如通过使用 void:

“吞噬”createProcess 的 return 值
main :: IO ()
main = do
    putStrLn "Pick a number?"
    putStrLn "From 1-5"
    numPick <- getLine
    putStrLn "Thank you for choosing a number."
    if numPick == "1" then  -- also fixed "1", because `getLine` returns String
       void $ createProcess (proc "/usr/bin/ls" [])
    else
       putStrLn "Do nothing"
    putStrLn "Were done here"

没有void的等效代码是:

if numPick == "1" then do
   createProcess (proc "/usr/bin/ls" [])
   return ()
else
   putStrLn "Do nothing"