比方说,在Haskell do-notation块中,我希望有一个变量is_root来表明我是否是根用户:
import System.Posix.User
main = do
uid <- getRealUserID
is_root <- return $ uid == 0那个恼人的uid变量只在这一个地方使用。我希望我可以这样写:
main = do
is_root <- getRealUserID == 0但这当然不会编译。
怎样才能去掉像uid这样的多余变量?这是我想出的最好的:
import System.Posix.User
main = do
is_root <- getRealUserID >>= return . ((==) 0)布拉赫!有没有更好的方法?
发布于 2014-08-15 02:15:16
一种方法是
fmap (== 0) getRealUserID发布于 2014-08-15 02:35:28
(我假设你的目标是限制uid的作用域,而不仅仅是为了它本身的无关紧要)
在这种简单的情况下,@pdw's answer可能是最好的选择。Control.Applicative中的操作符<$>和<*>在这里特别有用。
foo = do
are_same <- (==) <$> doThis <*> doThat在稍微复杂一点的情况下,您可以使用嵌套do
complicatedEq :: This -> That -> IO Bool
main = do
are_same <- do
this <- doThis
that <- doThatBasedOn this
complicatedEq this that
... rest ...任何很长的东西可能都应该是它自己的函数。
https://stackoverflow.com/questions/25314793
复制相似问题