Marcio
Marcio

Reputation: 351

How can I concatenate user input in a list

I would like to get codes from the user and insert it in a list, but the problem is when the user say that don't wanna insert more codes. I don't saved a list with the numbers because I'm using recursion to call the method again, so when I should return the list I don't have it.

insertCode :: [Integer]
insertCode = do
    putStrLn "Code:"
    code <- getLine
    putStrLn "Another? (Y/N)"
    if(resp == "Y" || resp == "y") then (read code::String->Integer):insertCode else --I don't know

I'm sorry for my stupids questions, I imagine that is obvious but I have a problem with functional programming

Upvotes: 2

Views: 90

Answers (1)

chepner
chepner

Reputation: 530872

First of all, your type signature is wrong. insertCode uses the IO monad, so the type must be IO [Integer]. You are also missing the conversion of code from a String to an Integer (I use readLn to accomplish that; you were trying to convert code into a function, not an Integer) and you are missing a getLine to get the Y/N response from the user.

Once that is fixed, you might write something like the following:

insertCode :: IO [Integer]
insertCode = do
    putStrLn "Code:"
    code <- readLn
    putStrLn "Another? (Y/N)"
    response <- getLine
    result <- if (response == "Y" || response == "y")
              then insertCode
              else return []
    return (code : result)

This is a little verbose, but tries to be explicit about how the monad is used. Whether the user enters Y or N, code must be appended to a list extracted from a monad: either a list extracted from a recursive use of insertCode, or an explicit empty list.

Upvotes: 7

Related Questions