将Reader Monad用于配置文件

时间:2019-03-04 11:15:45

标签: haskell monads

我正在尝试创建一个简单的配置文件以从文件读取静态数据。 我使用ConfigFile-1.1.4中的示例从文件中读取数据,尽管我不理解代码中的某些内容,但确实可以正常工作。 但是我需要在我的应用程序中穿刺这个配置文件,并且我知道我需要为此使用readerT monad吗?

要从文件读取的代码的工作部分如下

getConfig = do
  config <- readConfig "config.cfg"
  putStrLn $ "The path value is: " ++ (path config)
  putStrLn $ "The filename value is: " ++ (fileName config)



readConfig :: String -> IO ConfigInfo
readConfig f = do
    rv <-
    runErrorT $
     do
      cp <- join $ liftIO $ readfile emptyCP f
      let x = cp
      -- read out the attributes
      pv <- get x "DEFAULT" "path"
      fv <- get x "DEFAULT" "filename"
      -- build the config value
      return (ConfigInfo {path = pv, fileName = fv})
    either (\x -> error (snd x)) (\x -> return x) rv

我有一个功能,

get :: ID -> Name -> IO Keys
get u n = do
    p <- readFile ("getthisvaluefromconfigfile" ++ "getfromConfigfile")
    .
    .
    .
    return (p, b)

从阅读的示例中,我能够理解Ask函数将为我返回环境,然后可以使用ConfigInfo的函数来提取值。

a)我只是无法理解如何在getConfig函数中将值加载到环境中?

b)以及如何在ask函数(获取)中指定要从哪个ConfigInfo实例读取?

我确实尝试研究,发现了一些使用阅读器monad的示例,但没有一个示例显示如何加载env。

0 个答案:

没有答案