2017-04-25 62 views
0

我失去了在搜索類似但不完全相同的錯誤後調試此問題的下一步的下一步。從this Haskell scriptPandoc返回任一種類型

import Text.Pandoc (writePlain, readHtml, def, pandocVersion) 

convert :: String -> String 
convert = writePlain def . readHtml def 

相關線是造成此錯誤:

Main.hs:11:28: error: 
    • Couldn't match type ‘Either 
          Text.Pandoc.Error.PandocError Text.Pandoc.Definition.Pandoc’ 
        with ‘Text.Pandoc.Definition.Pandoc’ 
     Expected type: String -> Text.Pandoc.Definition.Pandoc 
     Actual type: String 
        -> Either 
          Text.Pandoc.Error.PandocError Text.Pandoc.Definition.Pandoc 
    • In the second argument of ‘(.)’, namely ‘readHtml def’ 
     In the expression: writePlain def . readHtml def 
     In an equation for ‘convert’: 
      convert = writePlain def . readHtml def 

環境的詳細信息:

  • GHC 8.0.1
  • 驚天動地1.24
  • 拱64 4.10.9

pandoccabal install倒是

感謝回答,評論和抨擊靠牆頭幾個小時,如下工作方案:

import Network.HTTP.Conduit (simpleHttp) 
import Data.Text.Lazy as TL 
import Data.Text.Lazy.Encoding as TLE 
import Text.Pandoc 
import Text.Pandoc.Error 
import Data.Set 

htmlToPlainText :: String -> String 
htmlToPlainText = writePlain (def { 
    writerExtensions = Data.Set.filter (/= Ext_raw_html) (writerExtensions def) 
    }) . handleError . readHtml def 

main :: IO() 
main = do 
    response <- simpleHttp "https://leonstafford.github.io" 

    let body = TLE.decodeUtf8 (response) 
    let bodyAsString = TL.unpack (body) 

    putStrLn $ htmlToPlainText bodyAsString 

回答

2

看看你試圖組合的兩種功能的類型:

readHtml:: ReaderOptions Reader options -> String -> Either PandocError Pandoc

readHtml是一種可能失敗的操作。爲了表示這個,它返回或者一個PandocError或一個有效的Pandoc。

writePlain:: WriterOptions -> Pandoc -> String

writePlain預計只有有效Pandoc。

程序必須處理這兩種情況:

  1. readHtml返回左/誤差值
  2. readHtml回報右/有效值

這可以通過各種方式來完成,但對於例如:

import Text.Pandoc (writePlain, readHtml, def, pandocVersion) 

convert :: String -> String 
convert = case readHtml def of 
    Left err -> show err 
    Right doc -> writePlain def doc 

Either a b類似於Maybe a,如果您熟悉這一點,除非它在失敗的情況下可以有額外的信息。按照慣例,構造函數Left用於表示錯誤值,而構造函數Right用於表示正常值。

+1

更好地將'convert'的類型簽名更改爲'String - > PandocError String',以便此'convert'函數的調用者可以採取合理的步驟來對錯誤作出反應。類型系統試圖警告你,'String - > String'不適合這個函數。進一步的證據:你必須在你的'Left'中寫'show err',這顯然不是這個函數的好結果。 – amalloy