Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading