5

I'm learning Haskell and I would like to have user input x numbers into the console and store those numbers in array which can be passed on to my functions.

Unfortunately no matter what I try it doesn't work, here is my code:

-- Int Array
intArray :: Int -> IO [Int]
intArray 0 = []
intArray x = do
    str <- getLine
    nextInt <- intArray (x - 1)
    let int = read str :: Int
    return int:nextInt

-- Main Function
main = do
    array <- intArray 5
    putStrLn (show array)
0

1 Answer 1

7

You need an IO [Int] in your base case:

intArray 0 = return []

and you need to change the return in your recursive case to use the correct precedence:

return (int:nextInt)

As an aside, [Int] is a singly-linked list of ints, not an array. You could also simplify your function using replicateM from Control.Monad:

import Control.Monad
intArray i = replicateM i (fmap read getLine)
Sign up to request clarification or add additional context in comments.

5 Comments

aaa... I see, I forgot that return wraps things in IO stuff lol! And I have spent so much time trying to figure this out.
A bit off topic... is this a good way to store data into array or is there a more clever way?
@Reygoch - See update. If you want arrays in particular then Haskell has them in Data.Array
Also, fmap read getLine is otherwise known as readLn, except that the latter will give any parse errors immediately rather than when the value is used later.
@ØrjanJohansen, readLn is okay, but you need to catch an exception to deal with parse errors. The (non-standard) readMaybe and readEither seem a bit more Haskell-flavored.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.