如何在Haskell中将文件读取为字符串?

Jon*_*han 1 haskell

我是Haskell的初学者.我正在尝试使用该markdown库来转换mardown并将其插入由Blaze制作的网页中.我可以做这个:

readme :: Html
readme = do
  markdown def "#test"
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.但我不能这样做:

readme :: Html
readme = do
  readmeFile <- readFile "../README.md"
  markdown def readmeFile
Run Code Online (Sandbox Code Playgroud)

因为我得到错误:

Views/Home.hs:55:17: error:
    • Couldn't match type ‘IO’ with ‘Text.Blaze.Internal.MarkupM’
      Expected type: Text.Blaze.Internal.MarkupM String
        Actual type: IO String
    • In a stmt of a 'do' block: readmeFile <- readFile "../README.md"
      In the expression:
        do { readmeFile <- readFile "../README.md";
             markdown def readmeFile }
      In an equation for ‘readme’:
          readme
            = do { readmeFile <- readFile "../README.md";
                   markdown def readmeFile }

Views/Home.hs:56:16: error:
    • Couldn't match type ‘[Char]’ with ‘Data.Text.Internal.Lazy.Text’
      Expected type: Data.Text.Internal.Lazy.Text
        Actual type: String
    • In the second argument of ‘markdown’, namely ‘readmeFile’
      In a stmt of a 'do' block: markdown def readmeFile
      In the expression:
        do { readmeFile <- readFile "../README.md";
             markdown def readmeFile }
Run Code Online (Sandbox Code Playgroud)

我知道有一些简单的方法可以解决这个问题,但我不知道从哪里开始.这是我脚本的其余部分,如果它有助于将其上下文化.(它使用OverloadedStrings.)

lef*_*out 5

如果声明类型readme :: Html,则意味着readme它将是纯值,即适当的常量.因此,每次运行程序时保证都是相同的 - 很好的保证,但这也意味着你不能让它依赖于外部文件,这可能随时都会发生变化.

所以你想要的可能就是:

mkReadme :: IO Html
mkReadme = do
  readmeFile <- readFile "../README.md"
  return $ markdown def readmeFile
Run Code Online (Sandbox Code Playgroud)

几乎可以工作.不完全是因为readFile生成一个老式Stringmarkdown想要更高效的Text类型.易于修复:只需使用库中的相应readFile功能即可text.

import qualified Data.Text.Lazy.IO as Txt

...

mkReadme :: IO Html
mkReadme = do
  readmeFile <- Txt.readFile "../README.md"
  return $ markdown def readmeFile
Run Code Online (Sandbox Code Playgroud)

  • 你不能.如果你读了一个外部文件,那就是一个IO动作,没办法解决它.(严格来说这并不是真的,有很多方法可以解决它,但这些都是你不想使用的明显的黑客攻击.)你可以问的真正问题是:"如何_invoke_这样的`IO`动作实际使用在我的程序中生成的Html?" (2认同)