Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell store user input in array

Tags:

input

haskell

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)
like image 986
Reygoch Avatar asked Mar 16 '23 18:03

Reygoch


1 Answers

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)
like image 158
Lee Avatar answered Mar 23 '23 19:03

Lee