为Configurator编写配置的实例

时间:2014-11-26 20:33:30

标签: haskell

我正在使用Bryan O' Sullivan的Configurator库来提供数据库连接详细信息。 app.cfg包含以下内容

database {
  host = "localhost"
  port = 5432
  user = "mydb"
  db = "mydb_dev"
  password = ""
}

在我的Haskell代码中,我有相应的数据类型,即

data DBConnection = DBConnection 
  { host :: Text
  , port :: Int
  , user :: Text
  , database :: Text
  , password :: Text
  } deriving Show

我不确定如何为此类型编写Configured的实例。

显然,我可以使用lookup访问数据库配置的每个元素,获取IO Maybe a,然后从这些值构造,但是是否可以将其转换为类型类实例?

谢谢,

迈克尔

1 个答案:

答案 0 :(得分:2)

为什么需要类型类?手动提取配置非常容易:

import Control.Applicative
import Data.Configurator

getDBConnection :: Config -> IO DBConnection
getDBConnection cfg = DBConnection
    <$> get "host"
    <*> get "port"
    <*> get "db"
    <*> get "user"
    <*> get "password"
  where
    get :: Configured a => Name -> IO a
    get = require cfg

如果你不喜欢例外,这里有一个Maybe版本:

import Control.Applicative
import Control.Monad.Trans.Maybe
import Data.Configurator

getDBConnection :: Config -> IO (Maybe DBConnection)
getDBConnection cfg = runMaybeT $ DBConnection
    <$> get "host"
    <*> get "port"
    <*> get "db"
    <*> get "user"
    <*> get "password"
  where
    get :: Configured a => Name -> MaybeT IO a
    get = MaybeT . lookup cfg

真的没有必要使事情过于复杂。它只有十行代码。