Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing a readLine inside an if

Tags:

io

haskell

I'm writing a small command-line utility in Haskell which should accept a command with an optional command-line argument - but if the argument is not present, the user should be prompted to enter it*. For example:

$ my_prog add item_name
Adding... done

$ my_prog add
Enter item name: item_name
Adding... done

My initial attempt looked something like this:

add args = do
    let id = if length args > 0
        then head args
        else input where
            input <- readLine
    -- Do stuff with id
    putStrLn id

Which fails to parse at the <-.

*I have since decided that this is a silly idea, but I thought I'd ask the question anyway.

like image 763
Daniel Buckmaster Avatar asked Dec 31 '25 13:12

Daniel Buckmaster


1 Answers

You are attempting to use the do-notation inside the if, this will not work (and besides, won't typecheck since the whole if is outside the IO monad).

add args = do
    id <- if length args > 0
              then return $ head args
              else readLine
    putStrLn id
like image 133
Koterpillar Avatar answered Jan 02 '26 09:01

Koterpillar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!