Doing a readLine inside an if

haskell, io

Solution

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

Problem

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.

Original source