I have the following snippet of code:
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)
How to write this code in ‘nice Haskell’? I was thinking about the MaybeT monad but somehow wasn’t able make it work. I was trying to do some ‘lifting’, but wasn’t able to stich the types together. I can change the signature of the getIfaceAddr/getDestAddr.
As a sidenote: why is inet_ntoa ‘HostAddress -> IO String’? I don’t think there are any side effects, are they?
Oh my, what is that
fromJust? IfgetIfaceAddrreturnsNothing, this code will crash your program.The
MaybeTsolution looks like this:The types for the first line fit together like this:
Remember that your code is going to have type
MaybeT IO something, so you have torunMaybeTto get it back intoIObefore binding it tomain.