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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With