【问题标题】:Getting error due to IO a type of parameter由于 IO 一种参数而出现错误
【发布时间】:2017-01-16 22:48:29
【问题描述】:

我正在实现如下功能: 用户将通过 HTTP 请求请求目录内容。目录路径将在请求中传递。作为响应,我将发送一个 JSON,其中包含该目录路径的文件列表。处理 IO 错误处理。 我已经实现了大部分。但我收到一个错误。错误是:

Couldn't match expected type ‘Either IOException [FilePath]’
            with actual type ‘IO (Either IOException [FilePath])’
• In the first argument of ‘getJsonRepForFiles’, namely ‘files’

sn-p代码如下:

getInfoOfDirR::Handler Value
getInfoOfDirR = do
             -- files will have type IO (Either IOException [FilePath])
                     files <- fmap (getListOfFiles.(Data.Text.unpack).fromJust) $ lookupGetParam "dirpath"
                     getJsonRepForFiles files

获取文件列表的函数:

-- This eliminates the hidden files from the results
getListOfFiles::FilePath -> IO (Either IOException [FilePath])
getListOfFiles fpath = try (fmap (filter $ not.isHiddenFile) $  FS.getDirectoryContents fpath)::IO (Either IOException [FilePath])

获取目录中文件的 JSON 表示的函数:

getJsonRepForFiles::Monad m => (Either IOException [FilePath]) -> m Value
getJsonRepForFiles (Left e) = returnJson $ "An error occurred" ++ show e
getJsonRepForFiles (Right files) = returnJson files

注意getInfoOfDirR 的类型是Handler Value 我在 Haskell 的 Yesod 框架中实现了这一点。 我是 Haskell 的新手。我有点理解为什么会出现错误。 但我无法修复它。 请帮忙。 提前致谢。

【问题讨论】:

  • 请注意,我尝试过使用 liftIO ,但也没有解决问题

标签: json haskell yesod


【解决方案1】:

我认为问题在于getListOfFiles 返回一个IO 类型的值,并且通过将它与fmap 一起使用,您正在创建一个Handler (IO _),并且do 块中的绑定仅解开@ 987654326@级别。

您可以尝试joining fmap 结果的两个级别,例如:

files <- join $ fmap (liftIO. ...

或者将getListOfFiles 调用移到fmap 应用程序之外,例如:

files <- liftIO . getListOfFiles =<< (fmap ...)

【讨论】:

  • 感谢您的回复。我尝试了这两种方法。现在我收到此错误:无法将类型“IO”与“HandlerT HelloWorld IO”匹配预期类型:HandlerT HelloWorld IO (Either IOException [FilePath]) 实际类型:IO (Either IOException [FilePath])
  • @ChetanYewale 我想那么你需要files &lt;- liftIO . getListOfFiles =&lt;&lt; (fmap ...)。抱歉,我假设 lookupGetParam 返回的类型为 IO
  • 非常感谢。那行得通。我想问你一些事情,我是 Haskell 的新手。我了解函数式编程风格。我也了解 Functors 和 Applicatives。我对 Monads 有点不舒服。有没有我可以做的练习题来逐渐帮助我在这些概念上变得更好?让我知道.. 我希望从使用 Applicatives/Functors/Monads 的小问题开始。我还想更好地了解类型系统并避免我发布的那种问题。有什么可以推荐的吗?
  • @ChetanYewale 实际上对我最有效的是实现Monad 类型类的一些实例以消除一些“魔力”。除此之外,做你看起来正在做的事情——在事情出现时处理它们(至少,除非我真的使用它来解决问题,否则似乎没有什么能对我产生影响) .
  • @ChetanYewale 你是否习惯于使用MaybeEither 的单子属性——一旦你达到某种状态,你“不能”走得更远?它归结为&gt;&gt;= :: m a -&gt; (a -&gt; m b) -&gt; m b。给定m a,您需要能够获取a 以传递给第二个参数以获取m b,但在Maybe aEither b a 的情况下,如果您有NothingLeft b没有a可以传递,所以你别无选择,只能停下来。
猜你喜欢
  • 2019-02-05
  • 1970-01-01
  • 2019-11-21
  • 2015-06-05
  • 2021-01-09
  • 2021-04-06
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多