parsing - Haskell - 读取文件并将数据作为参数传递给函数

标签 parsing haskell io

我试图从文件中获取一些数据,然后解析它并将其作为参数传递给另一个函数。

data LogLine = LogLine {
  name      :: String
, args1     :: String
, args2     :: String
, constant  :: String 
} deriving (Ord, Show, Eq)

main = do 
file <- readFile "foo"
let result = (parse final "Input" file) --Parses the file into the LogLine datatype
let firstargs = getFirstArgs result --Get the first argument out of the datatype
let secondargs = getSecondArgs result --Get the second argument out of the datatype
let constant = getConstant result --Get the constant out of the datatype
createGraph firstargs secondargs constant --THIS IS THE PROBLEM

问题是,每当我尝试读入一个文件时,它就会变成一个(IO String),并且无论我做什么,我总是必须携带 IO。 createGraph 函数声明为

createGraph :: String -> String -> String -> Argument

但每当我尝试执行最后一条语句时,它都会提示:

Couldn't match expected type `IO a0' with actual type `Argument'
In the return type of a call of `createGraph'

我不允许更改 createGraph 函数的返回类型,因为它是我需要向其提供参数的大型框架的一部分。 有哪些方法可以解决这个问题?

最佳答案

你为什么要这么做?

将值放入 IO monad 的唯一方法是使用 return。 您可以将对 createGraph 的调用包装到另一个函数中,例如

returnGraph a b c = return $ createGraph a b c

或者只是使用另一个 let 绑定(bind)并在需要时使用您的值。 我不知道你想在那里做什么。请向我们提供更多详细信息,例如你想如何处理返回值。

-- 根据我从您的评论中了解到的,您只需要返回参数,因此您唯一要做的就是返回 $ createGraph firstargs secondaryargs 常量并将函数从 main 重命名为其他名称,因为 main 必须具有类型 IO ()。

关于parsing - Haskell - 读取文件并将数据作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791192/

相关文章:

haskell - 固定长度和类型文字的列表

haskell - 打印所有可能的世界配置

c++ - 连接c/c++和python

parsing - 测试(自动)解析器的更好方法?

parsing - 在Dart中解析二进制DICOM数据

json - 如何在 Go 中逐字符读取文件

c# - .NET Framework中是否有ReadWord()方法?

haskell - Snap Web 框架中的自定义 404

java - 谁管理 System.in/System.out 的打开/关闭?

C fgets 缓冲区大小