user2957954
user2957954

Reputation: 1249

haskell read a file in array of Ints

I have a homework to sort a numbers that are to extract from a file.

Simple File Format:

45673
57879
28392
54950
23280
...

So I want to extract [Int] and than to apply my sort-function radix to it. I write in my file

readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile
makeInteger :: [String] -> [Int]
makeInteger = map read

and then I write in the command line

radix (makeInteger (readlines("111.txt")))

and then I have, off course, problems with type conversion from IO String to String. I tried to write

makeInteger :: IO [String] -> [Int]
makeInteger = map read

but it also doesn't work.

How do I work with pure data outside the IO monad?

Upvotes: 2

Views: 4166

Answers (1)

Alex Appetiti
Alex Appetiti

Reputation: 493

According to this, "the inability to "escape" from the monad is essential for monads like IO".

So you need to do something like:

readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile
makeInteger :: [String] -> [Int]
makeInteger = map read

main = do
  content <- readLines "111.txt"
  return (radix $ makeInteger content)

This "takes the content out" of the IO monad, applies the function you want on it, then puts it back into the IO monad again.

Upvotes: 2

Related Questions