打印Haskell是一个纯函数? [英] Is print Haskell a pure function?

查看:121
本文介绍了打印Haskell是一个纯函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中打印纯函数;为什么或者为什么不?我认为这不是因为它不会总是返回与纯函数相同的值。

解决方案

code> IO Int 并不是真正的 Int 。它更像是一张纸,上面写着嘿哈斯克尔运行时,请以这样和那样的方式产生 Int 值。即使运行时最终产生的 Int s不同,这张纸也是惰性的并且保持不变。



<通过将它分配给 main ,您可以将该纸张发送到运行时。如果 IO 动作永远不会以 main 的方式出现,而是在某个容器内衰减,它将永远不会被执行。

返回 IO 操作的函数与其他类似。他们总是返回同一张纸。运行时用这些指令做的事情是另一回事。



如果它们不是纯的,我们必须在改变前仔细考虑 p>

  foo ::(Int  - > IO Int) - > IO Int 
foo f = liftA2(+)(f 0)(f 0)

to

  foo ::(Int  - > IO Int) - > IO升级(+)x x 


Is print in Haskell a pure function; why or why not? I'm thinking it's not because it does not always return the same value as pure functions should.

解决方案

A value of type IO Int is not really an Int. It's more like a piece of paper which reads "hey Haskell runtime, please produce an Int value in such and such way". The piece of paper is inert and remains the same, even if the Ints eventually produced by the runtime are different.

You send the piece of paper to the runtime by assigning it to main. If the IO action never comes in the way of main and instead languishes inside some container, it will never get executed.

Functions that return IO actions are pure like the others. They always return the same piece of paper. What the runtime does with those instructions is another matter.

If they weren't pure, we would have to think twice before changing

foo :: (Int -> IO Int) -> IO Int
foo f = liftA2 (+) (f 0) (f 0)

to

foo :: (Int -> IO Int) -> IO Int
foo f = let x = f 0 in liftA2 (+) x x

这篇关于打印Haskell是一个纯函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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