如何堵住此类孔 2

2024-01-02

跟随从here https://stackoverflow.com/questions/58032008/how-to-plug-this-type-hole/58032339#58032339(我已将 main 中的代码重构为它自己的函数)我试图编译以下代码:

import qualified Data.Text as T
import Text.PDF.Info

title :: FilePath -> String
title path = do
  result <- pdfInfo path
  case result of
    Left someError -> do
      return "no title"
    Right info -> do
      case (pdfInfoTitle info) of
        Nothing -> return "no title"
        Just title -> return (T.unpack title)

我正进入(状态

    • Couldn't match type ‘[Char]’ with ‘Char’
      Expected type: [Char]
        Actual type: [[Char]]
    • In a stmt of a 'do' block: return "no title"
      In the expression: do return "no title"
      In a case alternative: Left someError -> do return "no title"
   |
14 |       return "no title"
   |       ^^^^^^^^^^^^^^^^^

对我来说,看起来我正在返回 String ([Char]) 类型,但我想不是。请指导,先谢谢了。

这是我希望实现的更大背景:

module Main where

import Control.Monad (liftM)
import Data.List (isSubsequenceOf, isSuffixOf)
import System.Directory (listDirectory)
import qualified Data.Text as T
import Text.PDF.Info

title :: FilePath -> String
title path = do
  result <- pdfInfo path
  case result of
    Left someError -> do
      return "no title"
    Right info -> do
      case (pdfInfoTitle info) of
        Nothing -> return "no title"
        Just title -> return (T.unpack title)

main :: IO ()
main = do
  print =<<
    liftM
      (filter
         (\path ->
            ((isSubsequenceOf "annotated" path) ||
             (isSubsequenceOf "annotated" (title path))) &&
            (isSuffixOf "pdf" path)))
      (listDirectory "/home/foo")

对我来说,看起来我正在返回一个String ([Char]) type.

No. return与大多数命令式语言一样,它不是返回内容的关键字。它是一个函数。的确return :: Monad m => a -> m a https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:return是一个函数“在 Monadic 类型中注入一个值".

The pdfInfo函数具有 as 类型pdfInfo :: MonadIO m => FilePath -> m (Either PDFInfoError PDFInfo) https://hackage.haskell.org/package/pdfinfo-1.5.4/docs/Text-PDF-Info.html#v:pdfInfo。所以我们需要使用一个MonadIO type:

title :: MonadIO m => FilePath -> m String
title path = do
    result <- pdfInfoTitle info
    case pdfInfo path of
        Left someError -> return "no title"
        Right info -> case (pdfInfoTitle info) of
            Nothing -> return "no title"
            Just title -> return (T.unpack title)

因此我们在这里返回一个m String。你可以看到一个MonadIO作为构建值的“配方”(这里是String)。不是一个String itself.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何堵住此类孔 2 的相关文章

随机推荐