Reygoch
Reygoch

Reputation: 1304

Haskell store user input in array

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)

Upvotes: 5

Views: 3001

Answers (1)

Lee
Lee

Reputation: 144206

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)

Upvotes: 7

Related Questions