我试图从文件中获取一些数据,然后解析它并将其作为参数传递给另一个函数。
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/