List 如何读取文件并转换[[Char]]中的内容IO字符串对字符串
我有这样一个文件:List 如何读取文件并转换[[Char]]中的内容IO字符串对字符串,list,haskell,List,Haskell,我有这样一个文件: 001 002 003 004 我需要建立一个列表[001002003004] 我试过这个 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 arg
001
002
003
004
我需要建立一个列表[001002003004]
我试过这个
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,但我不知道如何进行转换
编辑
我按照建议做了,但仍收到一条错误消息:
代码:
您可以使用以下行:
它使用IO是函子的事实。我猜map splitOn\n 001\n002\n会产生相同的类型错误。你确定你需要这张地图吗?检查splitOn的类型,你是对的。我不需要地图。但是在splitOn的第二个参数中,我需要一个[[Char]],但是文件是IO字符串。我试过这些建议,但我从来没有收到过同样的错误,我得到了!非常感谢。
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
fileContents <- lines <$> readFile "file.txt"