如何读取文件并转换[[Char]]中的内容? - IO String to String

时间:2017-03-27 14:29:37

标签: list haskell

我有一个这样的文件:

001
002
003
004

我需要构建一个列表[“001”,“002”,“003”,“004”]

我试过这个

map (splitOn "\n") (readFile "file.txt")

但我收到的消息是:

Couldn't match expected type `[[Char]]'
            with actual type `IO String'
In the return type of a call of `readFile'
In the second argument of `map', namely `(readFile "file.txt")'
In the expression: map (splitOn "") (readFile "file.txt")

我理解原因,我在map的第二个参数中需要一个[[Char]]而readFile返回一个IOString,但我不知道如何进行转换

修改

我做了建议,但我继续收到错误消息:

代码:

main = do
    fileContents <- readFile "file.txt"
    let modified = map (splitOn "\n") fileContents
    putStrLn modified

错误:

Couldn't match type `Char' with `[Char]'
Expected type: [[Char]]
  Actual type: String
In the second argument of `map', namely `fileContents'
In the expression: map (splitOn "") fileContents
In an equation for `string': string = map (splitOn "") fileContents

1 个答案:

答案 0 :(得分:1)

您可以使用lines

fileContents  <- lines <$> readFile "file.txt"

它使用IOFunctor的事实。