'try'可以决定程序何时停止

Brr*_*rch 2 haskell halting-problem

我有这个功能:

isUndefined :: () -> Bool    
isUndefined x = case unsafePerformIO $ (try (return $! x) :: IO (Either SomeException ())) of
                    Left _ -> True
                    Right _ -> False
Run Code Online (Sandbox Code Playgroud)

然后:

isUndefined () = False
isUndefined undefined = True
Run Code Online (Sandbox Code Playgroud)

解决停止问题.当然,这也可以扩展到其他类型.

我的问题:这怎么可能?难道Control.Exception.try真的破事吗?

chi*_*chi 8

Control.Exception.try真的破坏了这里的东西吗?

unsafePerformIO在这里破坏事物.在GHC中,undefined简单地引发异常而不是永远循环(这将是无益的).例外并不意味着被纯(非IO)代码捕获 - 实际上类型系统确实阻止你尝试那么多.

通过使用unsafe*功能,你告诉GHC"忽略一切,我知道我在做什么",所有安全带现在都关闭了.帮个忙,假装unsafe*东西不存在.