如何堵塞这种类型的孔? [英] How to plug this type hole?

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

问题描述

如果我返回的是表达式/值的类型:

If I have a returned type of an expression/value:

:: Control.Monad.IO.Class.MonadIO m =>
     m (Either PDFInfoError PDFInfo)

如何从中获取PDFInfo?也许更重要的是,一个人用什么过程弄清楚了这些事情.我想利用键入的漏洞或其他一些方法来自行推理这些类型的问题(无双关语).仍在阅读我的第一本Haskell书,但想了解经验更丰富的Haskeller如何使用工具解决此问题.

How do I get the PDFInfo out of it? Perhaps more importantly, what process does one use to figure such things out. I'd like to leverage typed holes or some other process to be able to reason through these types (no pun intended) of questions on my own. Still reading through my first Haskell book, but wanting to understand how a more experienced Haskeller would solve this using tools.

也许更有利于解决问题(尝试使用类型化的孔让ghc帮助我找到缺少的内容以获得PDFInfo结果,以便可以在其上调用pdfInfoTitle):

Perhaps it will help to have the greater context of the problem (attempting to use a typed hole to let ghc help me find what I am missing to get the PDFInfo result so that I can call pdfInfoTitle on it):

module Main where

import Text.PDF.Info

main :: IO ()
main = do
  pdfInfoTitle $ _ pdfInfo "foo.pdf" 

推荐答案

下面是一个编译示例:

module Main where

import Text.PDF.Info

main :: IO ()
main = do
  result <- pdfInfo "foo.pdf"
  case result of
    Left someError -> do
       putStrLn "Oh, no!"
       print someError
    Right info -> do
       putStrLn "OK! Got info!"
       print (pdfInfoTitle info)

想法是:在您的类型中,只要 m 属于 MonadIO 类,就可以根据需要选择monad m . m = IO 满足了这一要求,因此我们可以在 main 内部运行" pdfInfo"foo.pdf" ,非常类似于 putStrLn"hello" l<-geTLine 或任何其他IO操作.

The idea is: in your type, the monad m can be chosen as we wish as long as m belong to class MonadIO. m = IO satisfies that, so we can "run" pdfInfo "foo.pdf" inside main, much like putStrLn "hello" or l <- geTLine or any other IO action.

(每当您有 MonadIO m => ... 时,您总可以假装 m = IO .它们的类型比该类型更笼统,但保持简单的事情有助于直觉.)

(Whenever you have MonadIO m => ..., you can always pretend that m = IO. They type is slightly more general than that, but keeping things simple helps intuition.)

因此,我们可以使用结果<-pdfInfo"foo.pdf" .在这里, result 的类型为 m 内部的任何类型,即 PDFInfoError PDFInfo .因此, result 是错误(用 Left 包装)或实际信息(用 Right 包装).

So, we can use result <- pdfInfo "foo.pdf". Here, result has type whatever is inside m, that is Either PDFInfoError PDFInfo. Hence, result is either an error (wrapped under Left) or the actual info (wrapped using Right).

然后我们可以使用 case的结果分支两种可能性,并相应地进行处理.

We can then use case result of to branch on the two possibilities, and handle them accordingly.

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

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