如何插入此类型的孔2 [英] How to plug this type hole 2

查看:33
本文介绍了如何插入此类型的孔2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此处(我已将其重构将代码从main转换成自己的函数),我正在尝试编译以下代码:

Following along from here (I've refactored the code from main into its own function) I am trying to get the following code to compile:

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])类型,但我想不是.请提供指导,谢谢.

To me it looks like I am returning a String ([Char]) type, but I guess not. Guidance please, thanks in advance.

这里是我希望完成的工作的大背景:

Here it is in greater context of what I hope to accomplish:

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] )类型.

.与大多数命令式语言一样, return 不是返回内容的关键字.它是一个功能.实际上 return ::Monad m =>a-> 是"以单子类型注入值"的功能.

No. return is not, as in most imperative languages, a keyword to return content. It is a function. Indeed return :: Monad m => a -> m a is a function that "injects a value in a monadic type".

pdfInfo 函数的类型为

The pdfInfo function has as type pdfInfo :: MonadIO m => FilePath -> m (Either PDFInfoError PDFInfo). So we will need to use a 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字符串.您可以将 MonadIO 视为构造值的食谱"(此处为 String ).不是 String 本身.

We here thus return an m String. You can see a MonadIO as a "recipe" to construct a value (here a String). Not a String itself.

这篇关于如何插入此类型的孔2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆