Reputation: 1304
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
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