我试图通过目录递归,处理文件并将结果存储在数据库中,但我遇到了问题。
我正在尝试做的一个简化示例如下所示:
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
{-# LANGUAGE GADTs, FlexibleContexts #-}
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
import System.Environment (getArgs)
import System.Directory (canonicalizePath, getDirectoryContents, doesDirectoryExist, doesFileExist)
import System.FilePath (combine, takeExtension)
import Control.Monad (filterM, mapM_)
import Control.Monad.IO.Class (liftIO)
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistUpperCase|
File
path String
deriving (Show)
|]
main :: IO ()
main = do
args <- getArgs
path <- canonicalizePath $ head args
runSqlite "files.sqlite" $ do
runMigration migrateAll
liftIO $ processDirectory path
return ()
processDirectory path = files >>= mapM_ processFile >>
directories >>= mapM_ processDirectory
where contents = getDirectoryContents path >>=
return . map (combine path) . filter (`notElem` [".", ".."])
directories = contents >>= filterM doesDirectoryExist
files = contents >>= filterM doesFileExist
processFile path = insert $ File path
然而,上面没有编译,而是导致:
No instance for (PersistStore IO)
arising from a use of `processFile'
Possible fix: add an instance declaration for (PersistStore IO)
In the first argument of `mapM_', namely `processFile'
In the second argument of `(>>=)', namely `mapM_ processFile'
In the first argument of `(>>)', namely
`files >>= mapM_ processFile'
Failed, modules loaded: none.
这对我来说很有意义,因为 processFile 只是对插入的调用,PersistStore monad 的哪一部分(对吗?)不是 IO。我认为我需要的是一个单子变压器,但此时我遇到了一堵砖墙,这可能意味着我找错了树。