Search code examples
haskelldo-notation

How to avoid superfluous variables in do notation?


Say in a Haskell do-notation block, I wish to have a variable is_root indicating if I am root:

import System.Posix.User
main = do
    uid <- getRealUserID
    is_root <- return $ uid == 0

That annoying uid variable is only used in that one place. I wish instead I could write this:

main = do
    is_root <- getRealUserID == 0

But of course that won't compile.

How can I get rid of superfluous variables like uid? Here's the best I've come up with:

import System.Posix.User
main = do
    is_root <- getRealUserID >>= return . ((==) 0)

Blech! Is there a nicer way?


Solution

  • One way is

    fmap (== 0) getRealUserID