我正在尝试使用StateT monad读取配置文件部分。但遇到了点麻烦。有人能告诉我怎么做吗?
readSections :: StateT FilePath IO [T.Text]
readSections = do
path <- get
config <- readIniFile path
case config of
Left _ -> put [T.empty]
Right ini -> put (sections ini)发布于 2022-09-06 17:31:11
这段代码的问题在于,您试图使用FilePath类型的状态作为get函数的输入配置文件名,以及使用put的节名输出列表。至少对于put,类型是不正确的。FilePath不能是节名[T.Text]的列表。
由于您的一元返回值是[T.Text],所以您可能打算使用return而不是put。另外还有一个问题,因为readIniFile是IO操作,而不是StateT FilePath IO操作,因此需要使用liftIO将其提升到monad中。例如,以下内容将用于打字:
import Data.Ini
import Control.Monad.State
import qualified Data.Text as T
readSections :: StateT FilePath IO [T.Text]
readSections = do
path <- get
-- need to lift this action into StateT FilePath IO
config <- liftIO $ readIniFile path
case config of
-- use "return", not "put" here
Left _ -> return [T.empty]
Right ini -> return (sections ini)但是,这里可能没有必要使用状态。不应该只使用状态将输入传递给函数(或者将输出传递回函数) --这就是普通函数参数(和返回值)的目的。因此,您可以将其改写为:
readSections' :: FilePath -> IO [T.Text]
readSections' path = do
config <- readIniFile path
case config of
Left _ -> return [T.empty]
Right ini -> return (sections ini)https://stackoverflow.com/questions/73597644
复制相似问题