Since pattern matching the "pure" value to its constructor (namely ()) would force the value and so execute the unsafe action, if you write:main = do () <- return $ unsafePerformIO $ do print "test2" print "test"然后就可以了.还有其他方法可以强制执行此操作.您可以显式地进行模式匹配:There are other ways to force the action. You could pattern match explicitly:main = do case unsafePerformIO (print "test2") of () -> return () print "test"或使用 seq 如下:main = do unsafePerformIO (print "test2") `seq` print "test"或者像这样:main = do unsafePerformIO (print "test2") `seq` return () print "test"或使用严格的评估运算符:or use the strict evaluation operator:main = do return $! unsafePerformIO (print "test2") print "test"您还可以使用@Chris Stryczynski建议的 BangPatterns 扩展名.You can also use the BangPatterns extension as suggested by @Chris Stryczynski.我不确定哪种方法最好,尽管我倾向于使用($!)运算符作为最惯用的方法.I'm not sure which is best, though I'd lean towards using the ($!) operator as the most idiomatic.如@Carl所述,出于调试目的,使用 Debug.Trace 中的 trace 通常比直接调用 unsafePerformIO 更明智.因为这是从纯代码中打印调试信息的标准方式,并且因为实现比简单的 unsafePerformIO更具思想性.putStrLn .但是,它可能会出现相同的问题:As noted by @Carl, for debugging purposes, using trace from Debug.Trace is generally more sensible than calling unsafePerformIO directly, both because it's the standard way of printing debugging information from pure code and because the implementation is a little more thoughtful than a simple unsafePerformIO . putStrLn. However, it potentially exhibits the same issue:import Debug.Tracemain = do return $ trace "test2" () -- won't actually print anything print "test"相反,您可能需要使用上面的一种方法来强制其值:Instead, you need to force it's value, perhaps by using one of the methods above:import Debug.Tracemain = do return $! trace "test2" () -- with ($!) this works print "test" @Carl说 trace 具有可解决此问题的API时,他表示您通常在以下情况下使用trace:When @Carl says that trace has an API that works around this issue, he means that you normally use trace in a situation like:let value_i_actually_use = trace "my message" value_of_the_trace_expression当您实际使用(评估) trace 表达式的值时,将显示该消息.When you actually use (evaluate) the value of the trace expression, then the message will be displayed.然后 这篇关于如何在`unsafePerformIO`中强制评估IO操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-20 13:43