一个 Haskell 函数类型:IO String->细绳 [英] A Haskell function of type: IO String-> String

查看:34
本文介绍了一个 Haskell 函数类型:IO String->细绳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Haskell 写了一堆代码来创建文本索引.顶部函数如下所示:

I wrote a bunch of code in Haskell to create an index of a text. The top function looks like this:

index :: String -> [(String, [Integer])]
index a = [...]

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

Now I want to give this function a String read from a file:

index readFile "input.txt"

这是行不通的,因为 readFile 的类型是 FilePath -> IO String.

Which won't work because readFile is of type FilePath -> IO String.

无法匹配预期的类型字符串"针对推断类型 'IO String'

Couldn't match expected type 'String' against inferred type 'IO String'

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

I see the error, but I can't find any function with type:

IO String -> String

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

I guess the key to success lies somewhere under some Monads, but I could not find a way to solve my problem.

推荐答案

你可以很容易地编写一个函数来调用 readFile 操作,并将结果传递给你的索引函数.

You can easily enough write a function that calls the readFile action, and passes the result to your index function.

readAndIndex fileName = do
    text <- readFile fileName
    return $ index text

然而,IO monad 会污染所有使用它的东西,所以这个函数的类型是:

However, the IO monad taints everything that uses it, so this function has the type:

readAndIndex :: FilePath -> IO [(String, [Integer])]

这篇关于一个 Haskell 函数类型:IO String->细绳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆