9

我一直在尝试想出一种简单直观的方式来使用 Haskell 中的数据库。我从Yesod 书中获取了这段代码,并尝试对其进行清理,以便更容易理解和使用。

{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
{-# LANGUAGE GADTs, FlexibleContexts #-}

import Database.Persist
import Database.Persist.Sqlite (withSqliteConn, runSqlConn, runMigration)
import Database.Persist.TH (share, mkPersist, mkMigrate, sqlSettings, persist)

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist|
Person                              -- Table name
    name String                     -- String value
    age Int Maybe                   -- Numerical value
|]

updateDB x y = withSqliteConn "data.db" $ runSqlConn $ do
    runMigration migrateAll         -- Creates "Person" table if one doesn't exist
    insert $ Person x $ Just y      -- Inserts values into .db file

main = do
    updateDB "Frank Silver" 40      -- adds name "Frank Silver" and age "40" to data.db file

这段代码几乎可以工作,但我收到以下我无法解决的错误。

No instance for (Control.Monad.Trans.Resource.MonadResource IO)
      arising from a use of `updateDB'
    Possible fix:
      add an instance declaration for
      (Control.Monad.Trans.Resource.MonadResource IO)
    In a stmt of a 'do' block: updateDB "Frank Silver" 40
    In the expression: do { updateDB "Frank Silver" 40 }
    In an equation for `main': main = do { updateDB "Frank Silver" 40 }

任何指出我正确方向的建议将不胜感激。

4

1 回答 1

9

main = do
    updateDB "Frank Silver" 40

的类型updateDB "Frank Silver" 40被推断为IO (),因为这是默认类型main(它必须具有IO asome的类型a)。但是从定义来看,它的类型被推断为MonadRescource m => m a对于某些a(可能是a = (),但我不确定),并且没有instance MonadResource IO. 所以你需要一些东西来将 a 转换updateDB为一个IO动作,通常的方法是runResourceT,它将 aResourceT m a转换为一个m a(这里m = IO),所以

main = runResourceT $ updateDB "Frank Silver" 40

作品。

于 2013-02-24T00:13:23.260 回答