如何将readProcess monad与Haskell中的where组合?

时间:2015-02-14 22:17:30

标签: haskell monads

以下脚本旨在作为已发布和正在使用的Pandoc Haskell filter script的扩展。添加的内容是调用shell命令curl

#!/usr/bin/env runhaskell
-- svgtex.hs
import Text.Pandoc.JSON
import System.Process

curl latex = readProcess "curl" ["-d", "type=tex&q=" ++ latex, "http://localhost:16000"] ""

main = toJSONFilter svgtex
  where svgtex (Math style latex) = do
            svg <- curl latex
            return (Math style (svg))
        svgtex x = x

然而,对于Haskell函数式编程来说是全新的,我的脚本失败并不奇怪:

Couldn't match expected type `IO Inline' with actual type `Inline'
In the expression: x
In an equation for `svgtex': svgtex x = x
In an equation for `main':
...

尽管跳过了一些在线Haskell教程和StackExchange Q&amp; As,monad的概念仍未完全明白。因此,非常感谢上面脚本中有关所有错误的详细解释!

1 个答案:

答案 0 :(得分:3)

问题在于:

    svgtex x = x

编者抱怨说

Couldn't match expected type `IO Inline' with actual type `Inline'

因为xInline,而svgtex必须返回IO Inline。要将x注入IO monad,我们只需使用return函数

    svgtex x = return x

要完全了解正在发生的事情,请参阅任何monad教程(或LYAH)。粗略地说,类型IO Inline的值表示可以执行任何数量的I / O并最终返回类型Inline的值的操作。 return函数用于将纯值转换为虚拟IO操作,该操作不执行任何I / O,只返回结果。