提问人:Big Man 提问时间:12/16/2022 更新时间:12/16/2022 访问量:82
无法从 haskell 中的文件中读取
Can't read from a file in haskell
问:
我一直在尝试在 haskell 中使用 readFile 语法,但是当我尝试这样做时,我收到一个我不知道如何修复的错误。
我的代码:
import System.Environment
maze_path = "maze2.txt"
get_maze :: String -> IO [String]
get_maze file =
do
x <- readFile file
return (read x)
错误:
*** Exception: Prelude.read: no parse
此错误是通过使用“mape_path”字符串执行函数“get_maze”而得到的。
我只是想将文件的全部内容转换为常规字符串格式,任何帮助将不胜感激。
答:
2赞
Markus Mayr
12/16/2022
#1
线
x <- readFile file
按照您的假设工作,并将给定文件的内容作为 .该错误由函数引发。x
String
read
该函数将 a 转换为给定的输出类型。在您的例子中,给定 类型 ,Haskell 确定必须具有 .因此,文本文件应包含一个格式化的字符串数组,基本上是您通过编写例如 ().read
String
get_maze :: String -> IO [String]
read
String -> [String]
show ["Hello", "World"]
["Hello","World"]
该文件似乎没有以这种方式格式化。如果无法解析输入,它将抛出上面的错误。在 Haskell 中有更强大的方法来解析内容,但我可以想象您的文件根本没有以这种方式格式化,并且您想使用不同的函数。read
例如,如果你只想得到一个行列表,Haskell 中有一个函数,它将一个字符串拆分为一个行列表。lines :: String -> [String]
下一个:使用表达式树解析输入
评论
read
readFile
[String]
lines x