一个类型为Haskell的函数:IO String->串 [英] A Haskell function of type: IO String-> String

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

问题描述

我在Haskell中编写了一堆代码来创建一个文本索引。顶部功能如下所示:

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

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

$ $ p $ $ $ c $ index index readFile input.txt

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


无法匹配预期类型'字符串'
对比推断类型'IO字符串'


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

  IO String  - >字符串

我猜成功的关键在于某些Monad下的某处,但我找不到办法解决我的问题。您可以轻松地编写一个调用readFile操作的函数,并将结果传递给您的索引函数。

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

但是,IO monad会污染使用它的所有内容,所以此函数的类型为:

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


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"

Which won't work because readFile is of type FilePath -> 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

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

解决方案

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

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

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

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

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