How can i store a line by line user input as an integer list in Haskell?

Viewed 174

i am extremely new to haskell, and i was tasked with creating a program that merge sorts n number of integers. The program asks for how many elements that it is going to be sorting, and the elements to be sorted would be inputted line by line. I haven't even gotten to sorting it yet, but i am having trouble with storing the line by line input in a list. This is what i have so far.

storedelems = []

inputelems 0 = return storedelems
inputelems n = 
 do
    storedelems <- getLine 
    inputelems (n-1)


main = (inputelems 4)

When i finish entering the line by line numbers i want to sort, it just returns []

1 Answers

When you run inputelems 4 you just read to storedelems one line and just forget it, and after all unmemorable reads you just return global storedelems which you defined as [].

For you there is function replicateM. For using it you firstly must import module Control.Monad:

import Control.Monad (replicateM)

Now you can use it so:

main = replicateM 4 getLine

So, now main reads 4 lines and create list of read strings.

If you want list of integers, you can modify main so:

main :: IO [Int]
main = replicateM 4 (read <$> getLine)

But you have to realise that it is wrong if your function will be named main because main is special function which must has type IO ().

You also can modify your solution so:

inputelems 0 = return []
inputelems n = 
 do
    storedelem <- getLine 
    (storedelem : ) <$> inputelems (n-1)

Now your storedelem won't be forgotten.

Related