Eliminate repetitive monad/list code

I have code which looks like this: foo :: IO A bar :: Bool -> A -> Int -> Bool -> IO () do x <- foo y <- foo z <- foo bar True x 1 False bar True y 2 False bar True z 3 False What is the best way to factor it, including eliminating the temporary x,y,z variables? I can get this down to foo :: IO A bar :: Bool -> A -> Int -> Bool -> IO () bar' a b = bar True a b False do x <- foo y <- foo z <- foo bar x 1 bar y 2 bar z 3 but I don't know what to do next. Is there some form of list comprehension or combination of map and lift which will eliminate the repetition?

Hi!
do
x <- foo
bar' x 1
is equivalent to:
foo >>= \ x -> bar' x 1
which is equivalent to
flip bar' 1 =<< foo
so, for the whole thing, you can say:
do
flip bar' 1 =<< foo
flip bar' 2 =<< foo
flip bar' 3 =<< foo
and if you define bar'' as,
bar'' = flip bar'
then it boils down to,
do
bar'' 1 =<< foo
bar'' 2 =<< foo
bar'' 3 =<< foo
To further get rid of the foo's, you might want to have a look at the
Reader monad. But that would be overkill, I think.
HTH,
On 4 November 2010 16:19, John Smith
I have code which looks like this:
foo :: IO A
bar :: Bool -> A -> Int -> Bool -> IO ()
do x <- foo y <- foo z <- foo
bar True x 1 False bar True y 2 False bar True z 3 False
What is the best way to factor it, including eliminating the temporary x,y,z variables? I can get this down to
foo :: IO A
bar :: Bool -> A -> Int -> Bool -> IO ()
bar' a b = bar True a b False
do x <- foo y <- foo z <- foo
bar x 1 bar y 2 bar z 3
but I don't know what to do next. Is there some form of list comprehension or combination of map and lift which will eliminate the repetition?
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners
-- Ozgur Akgun

On 4 November 2010 17:19, John Smith
foo :: IO A
bar :: Bool -> A -> Int -> Bool -> IO ()
bar' a b = bar True a b False
do x <- foo y <- foo z <- foo
bar x 1 bar y 2 bar z 3
but I don't know what to do next. Is there some form of list comprehension or combination of map and lift which will eliminate the repetition?
mapM_ (\x -> foo >>= flip bar x) [1,2,3]

Thank you very much, this is just the right solution. On 04/11/2010 18:33, Tobias Brandt wrote:
On 4 November 2010 17:19, John Smith
wrote: foo :: IO A
bar :: Bool -> A -> Int -> Bool -> IO ()
bar' a b = bar True a b False
do x<- foo y<- foo z<- foo
bar x 1 bar y 2 bar z 3
but I don't know what to do next. Is there some form of list comprehension or combination of map and lift which will eliminate the repetition?
mapM_ (\x -> foo>>= flip bar x) [1,2,3]
participants (3)
-
John Smith
-
Ozgur Akgun
-
Tobias Brandt