鉴于此代码片段:
someFunction x = print x `seq` 1
main = do print (someFunction "test")
为什么不print x
print test
代码什么时候执行?
$./seq_test
1
如果我把它替换为error
我可以检查左操作数seq
is确实评价过。
我怎样才能达到我的预期输出:
test
1
仅修改someFunction
?
评估一个IO
行动什么也不做。这是正确的!
If you like, values of IO
type are merely "instruction lists". So all you do with that seq
is force the program to be sure1 of what should be done if the action was actually used. And using an action has nothing to do with evaluation, it means monadically binding it to the main
call. But since, as you say, someFunction
is a function with a non-monadic signature, that can't happen here.
你可以做什么...但不要, is
import Foreign
someFunction x = unsafePerformIO (print x) `seq` 1
这实际上将评估与IO
执行。这在 Haskell 中通常是一个非常糟糕的主意,因为评估可能以完全不可预见的顺序发生,可能与您想象的次数不同(因为编译器假设引用透明),以及其他混乱的场景。
正确的解决方案是将签名更改为单子:
someFunction :: Int -> IO Int
someFunction x = do
print x
return 1
main = do
y <- someFunction "test"
print y
1And as it happens, the program is as sure as possible anyway, even without seq
. Any more details can only be obtained by executing the action.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)