Haskell中的打印是纯功能吗?

Haskell中的打印是纯功能吗?

问题描述:

在Haskell中print是纯函数吗?为什么或者为什么不?我认为不是,因为它并不总是返回与纯函数相同的值.

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.

类型IO Int的值实际上不是Int.它更像是一张纸,上面写着嘿,Haskell运行时,请以这种方式产生一个Int值".这张纸是惰性的,即使运行时最终生成的Int是不同的,也保持不变.

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.

您可以通过将纸张分配给main来将其发送到运行时.如果IO动作永远不会妨碍main的执行,而是在某个容器内倾斜,它将永远不会执行.

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.

返回IO动作的函数与其他函数一样是纯函数.他们总是返回同一张纸.运行时对这些指令的处理是另一回事.

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)

收件人:

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