如何 understand/use Haskell 修复函数
How to understand/use Haskell fix function
我在 xmonad
包中看到以下代码:
-- | Ignore SIGPIPE to avoid termination when a pipe is full, and SIGCHLD to
-- avoid zombie processes, and clean up any extant zombie processes.
installSignalHandlers :: MonadIO m => m ()
installSignalHandlers = io $ do
installHandler openEndedPipe Ignore Nothing
installHandler sigCHLD Ignore Nothing
(try :: IO a -> IO (Either SomeException a))
$ fix $ \more -> do
x <- getAnyProcessStatus False False
when (isJust x) more
return ()
这个fix
函数好像来自Data.Function
但是我不明白它在这里是如何使用的,什么时候会有人使用这个修复功能?
fix
是实现递归的基本工具。它总是可以被递归 let
替换——反之亦然,递归 let
可以变成对 fix
的调用。在这个例子中,
fix $ \more -> do
x <- getAnyProcessStatus False False
when (isJust x) more
相当于
let more = do
x <- getAnyProcessStatus False False
when (isJust x) more
in more
并且实质上是在实现一个循环,该循环调用 getAnyProcessStatus False False
直到 returns Nothing
.
我在 xmonad
包中看到以下代码:
-- | Ignore SIGPIPE to avoid termination when a pipe is full, and SIGCHLD to
-- avoid zombie processes, and clean up any extant zombie processes.
installSignalHandlers :: MonadIO m => m ()
installSignalHandlers = io $ do
installHandler openEndedPipe Ignore Nothing
installHandler sigCHLD Ignore Nothing
(try :: IO a -> IO (Either SomeException a))
$ fix $ \more -> do
x <- getAnyProcessStatus False False
when (isJust x) more
return ()
这个fix
函数好像来自Data.Function
但是我不明白它在这里是如何使用的,什么时候会有人使用这个修复功能?
fix
是实现递归的基本工具。它总是可以被递归 let
替换——反之亦然,递归 let
可以变成对 fix
的调用。在这个例子中,
fix $ \more -> do
x <- getAnyProcessStatus False False
when (isJust x) more
相当于
let more = do
x <- getAnyProcessStatus False False
when (isJust x) more
in more
并且实质上是在实现一个循环,该循环调用 getAnyProcessStatus False False
直到 returns Nothing
.