2017-12-27 193 views
1

我正在嘗試閱讀Haskell中的簡單.ini文件,以用作我的應用程序的配置。我不是Haskell的專家,所以我可能會錯過簡單的東西。閱讀Haskell中的ini文件

到目前爲止,我的簡化代碼如下所示

{-# LANGUAGE OverloadedStrings   #-} 

import Data.Ini 

main :: IO() 
main = do 
    config <- readIniFile "config.ini" 
    p <- lookupValue "NETWORK" "port" config 

    ... 

編譯器給了我這個錯誤

無法匹配,期望型「燕麗」與實際類型的「任意字符串燕麗」在第三個參數lookupValue即'config'。

我看着Data.Ini的docs,但我找不到如何使用Api的任何示例。

任何幫助將非常感激。

+0

聽起來配置返回一個字符串要麼燕麗,而不僅僅是一個ini。只是在配置模式匹配,'左犯錯的情況下配置 - > putStrLn錯誤;正確的c - >做lookupValue ...' – Zpalmtree

回答

2

問題是readIniFile返回IO (Either String Ini)。並且lookupValue預計值爲Ini。因此,您必須從Either中解開ini值並提供適當的錯誤處理。

我敢肯定,有一個更單一和富有表現力的方式來解決這個問題,但這裏有一個解決方案。

{-# LANGUAGE OverloadedStrings #-} 

import Data.Ini 

main :: IO() 
main = do 
    config <- readIniFile "config.ini" 
    case config of 
     Right ini -> do 
      let p = lookupValue "NETWORK" "port" ini 
      putStrLn $ case p of 
         Left s -> s 
         Right t -> show t 
     Left s -> putStrLn s 
2

讀取文檔,readIniFile返回IO (Either String Ini),但lookupValue第三個參數必須是Ini(並返回一個Either String Text)。您需要使用case語句來檢索ini:

result <- readIniFile "config.ini" 
p <- case result of 
     Left str -> Left str 
     Right ini -> lookupValue "NETWORK" "port" ini 

讀取源代碼時,左判別式似乎用於報告錯誤消息。

如果你想更大膽的嘗試,你可以使用一個單子:https://hackage.haskell.org/package/base-4.10.1.0/docs/Data-Either.html#t:Either

result <- readIniFile "config.ini" 
p <- (result >>= (lookupValue "Network" "port"))