[Haskell-cafe] foreach

Donald Bruce Stewart dons at cse.unsw.edu.au
Wed Sep 13 00:16:17 EDT 2006


lemmih:
> On 9/13/06, Tim Newsham <newsham at lava.net> wrote:
> >I was rewriting some non-haskell code in haskell and came up with this
> >construct:
> >
> >   foreach l f = mapM_ f l
> >
> >   main = do
> >       args <- getArgs
> >       foreach args (\arg -> do
> >           foreach [1..3] (\n -> do
> >               putStrLn ((show n) ++ ") " ++ arg)
> >            )
> >        )
> >
> >which is reminiscent of foreach in other languages.  Seems fairly
> >useful and I was wondering how hard it would be to add some syntactic
> >sugar to the "do" construct to make it a little prettier (ie.
> >not require the parenthesis, binding and nested do, as:
> >
> >   main = do
> >       args <- getArgs
> >       foreach args arg
> >           foreach [1..3] n
> >               putStrLn ((show n) ++ ") " ++ arg)
> >
> >would this type of transformation be possible with template haskell
> >or does this need stronger support from the parser to pull off?
> 
> How about:
> 
>  main = do
>    args <- getArgs
>    flip mapM_ args $ \arg ->
>      flip mapM_ [1..3] $ \n ->
>        putStrLn $ show n ++ ") " ++ arg
> 

Which is, with current Control.Monad:

   main = do
     args <- getArgs
     forM_ args $ \arg ->
       forM_ [1..3] $ \n ->
         putStrLn $ show n ++ ") " ++ arg

I think Tim is looking for an if-then-else "real syntax" feel to his
`foreach' though. I.e. TH or some small preprocessor.
  
-- Don


More information about the Haskell-Cafe mailing list