相关疑难解决方法(0)

Haskell函数类型:IO String-> String

我在Haskell中编写了一堆代码来创建文本索引.top函数如下所示:

index :: String -> [(String, [Integer])]
index a = [...]
Run Code Online (Sandbox Code Playgroud)

现在我想给这个函数一个从文件读取的字符串:

index readFile "input.txt"
Run Code Online (Sandbox Code Playgroud)

哪个不起作用,因为readFile的类型为FilePath - > IO String.

无法将预期类型'String'与推断类型'IO String'匹配

我看到错误,但我找不到任何类型的函数:

IO String -> String
Run Code Online (Sandbox Code Playgroud)

我想成功的关键在于Monads的某些地方,但我找不到解决问题的方法.

io monads haskell readfile

35
推荐指数
4
解决办法
3万
查看次数

逐行读取文件

我正在尝试逐行读取文件,但是当我到达EOF时我不知道如何停止.

我有这个代码:

readWholeFile = do inputFile <- openFile "example.txt" ReadMode
                readALine inputFile

readALine x = do y <- hGetLine x
                 print y
                 readALine x
Run Code Online (Sandbox Code Playgroud)

它显然总是终止提出异常.

我怎么解决?

编辑:确切的错误消息是:

*** Exception: example.txt: hGetLine: end of file
Run Code Online (Sandbox Code Playgroud)

haskell

7
推荐指数
3
解决办法
6936
查看次数

标签 统计

haskell ×2

io ×1

monads ×1

readfile ×1