简体   繁体   English

将配置文件读入 Haskell 时发生 IO

[英]Fighting IO when reading a configuration file into Haskell

I have input data intended for my yet-to-be-written Haskell applications, which reside in a file.我有用于我尚未编写的 Haskell 应用程序的输入数据,这些数据驻留在一个文件中。 I don't update the file.我不更新文件。 I just need to read the file and feed it into my Haskell function which expects a list of strings.我只需要读取文件并将其输入到需要字符串列表的 Haskell 函数中。 But reading the file of course yields IO data objects.但是读取文件当然会产生IO数据对象。 I have learned that using the <- operation can "take out" somehow the strings packed in an IO structure, so I tried this attempt:我了解到使用<-操作可以以某种方式“取出”打包在IO结构中的字符串,因此我尝试了以下尝试:

run :: [String]
run = do
  datadef_content <- readFile "play.txt" -- yields a String
  let datadef = lines datadef_content -- should be a [String]
  return datadef

I placed this into a file play.hs and loaded it from ghci by我把它放到一个文件play.hs并从 ghci 加载它

:l play

To my surprise, I got the error message for the readFile line令我惊讶的是,我收到了readFile行的错误消息

 Couldn't match type 'IO' with '[]' Expected type: [String] Actual type: IO String

and for the return the error messagereturn错误消息

 Couldn't match type '[Char]' with 'Char' Expected type: [String] Actual type: [[String]]

The first seems to indicate that I couldn't get rid of the IO , and the last message seems to suggest, that lines would return a list of list of strings, which also doesn't make sense to me.第一个似乎表明,我无法摆脱的IO ,以及最后的消息似乎表明,该lines将返回字符串,这也没有任何意义,我的名单列表。

How can I do this correctly?我怎样才能正确地做到这一点?

You declare run to be a [String] value.您将run声明为[String]值。 But return is not a keyword that provides the return value of a function;但是return不是提供函数返回值的关键字; it is a function, with type Monad m => a -> ma .一个函数,类型为Monad m => a -> ma return datadef produces a value of type IO [String] , which becomes the return value of the function. return datadef产生一个IO [String]类型的值,它成为函数的返回值。

The solution is to provide the correct return type for run :解决方案是为run提供正确的返回类型:

run :: IO [String]
run = do
    ...

run can also be defined more succinctly as run也可以更简洁地定义为

run = fmap lines (readFile "play.txt")

Though the do syntax suggests is, there is no way to pull a value out of an IO action;尽管do语法表明是,但无法IO操作中提取值; all you can do is "push" the call to lines into the action.您所能做的就是将lines调用“推送”操作中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM