繁体   English   中英

用Writer monad组成函数?

[英]Function composition with the Writer monad?

我正在研究Writer monad,并具有以下内容:

myFunction :: Int -> Int -> Writer String Int
myFunction e1 e2 
   | e1 > e2 = do
      tell ("E1 greater")
      return (e1)
   | otherwise = do
      tell ("E2 greater")
      return (e2)

main = do
-- execWriter :: Writer w a -> w 
   print $ execWriter . myFunction 1 2 

错误:

"Couldn't match type ‘WriterT String Data.Functor.Identity.Identity Int’with ‘a0 -> Writer c0 a1’
  Expected type: a0 -> Writer c0 a1
    Actual type: Writer String Int"

为什么使用会出现此计算错误. 而不是$ 也许我对功能组成的理解不正确?

具有的函数组成. 表示结果合成将收到一个参数。

这部分:

execWriter . myFunction 1 2

可以这样更明确地编写:

(\x -> execWriter (myFunction 1 2 x))

由于myFunction仅接受两个参数,因此会出现编译错误。

您是否在代码中使用了$ ,如下所示:

execWriter $ myFunction 1 2

扩展后的结果代码与此等效:

execWriter (myFunction 1 2)

哪个有效

除了Chad所说的之外,发生这种情况是因为常规函数应用程序(不使用$ )比所有运算符(中缀函数)(包括)具有更高的优先级.

如果您这样编写示例,则该示例将有效:

(execWriter . myFunction 1) 2

等效于:

(\x -> execWriter (myFunction 1 x)) 2

然后评估为:

execWriter (myFunction 1 2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM