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



这是我的代码

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"

我希望用户选择一个数字,然后从所选择的数字中运行系统进程。我是哈斯克尔的新手,有人知道我做错了什么吗?

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

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返回与进程关联的多个句柄,而putStrLn不返回任何句柄(IO ()(。因为if-else-表达式的两个部分都需要是相同的类型,所以需要统一这些函数调用,例如通过";吞咽;使用void:的createProcess的返回值

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"

最新更新