Haskell - Get user input in do block and use it in if statement
Here is my code
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"
I want a user to pick a number and from the number that gets picked a system process is ran. I am new to Haskell does anyone know what am I doing wrong?
I am getting the following error when trying to compile.
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"
| ^^^^^^^^^^^^^^^^^^^^^
Solution 1:
createProcess
returns a number of handles associated with the process, while putStrLn
returns nothing (IO ()
). Because both parts of the if-else
-expression need to be of the same type, you need to unify those function calls, e.g. by "swallowing" the createProcess
's return value using void
:
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"
The equivalent code without void
is:
if numPick == "1" then do
createProcess (proc "/usr/bin/ls" [])
return ()
else
putStrLn "Do nothing"