“如果”分支我有下面的代码片段:如何写常见于哈斯克尔
srcaddr <- getIfaceAddr iface >>= inet_ntoa . fromJust
dstaddr <- getDestAddr iface >>= inet_ntoa . fromJust
-- I want to perform actions only if neither getIfaceAddr
-- nor getDestAddr returned Nothing
action1 srcaddr dstaddr
action2 srcaddr dstaddr
action3 srcaddr dstaddr
getIfaceAddr :: String -> IO (Maybe HostAddress)
getDestAddr :: String -> IO (Maybe HostAddress)
如何写“好哈斯克尔”这个代码?我正在考虑MaybeT monad,但不知何故无法实现。我试图做一些“提升”,但无法将这些类型拼凑在一起。我可以更改getIfaceAddr/getDestAddr的签名。
作为旁注:为什么inet_ntoa'HostAddress - > IO String'?我不认为有任何副作用,是吗?
是的 - 我可以将getIfaceAddr的结果传递给辅助函数,并在那里执行inet_ntoa。对于所有内容,我只是对“创建帮助函数”的答案感到有些厌倦。 – ondra 2010-11-28 13:33:58
幸运的是,您可以使用`liftM2`函数来控制``Maybe` monad`从Control.Monad`,而不是自己滚动。 – nponeccop 2011-11-29 16:31:35