打印Haskell是一个纯函数? [英] Is print Haskell a pure function?
问题描述
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 Int
s 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屋!