2

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?

4

1 回答 1

2

据此,“无法从 monad 中“逃脱”对于像 IO这样的 monad 来说是必不可少的。

因此,您需要执行以下操作:

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

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

这从 IO monad 中“取出内容”,在其上应用您想要的功能,然后再次将其放回 IO monad。

于 2013-11-05T21:18:33.673 回答