[Haskell-beginners] general structuring of "foreach" logic in IO

John M. Dlugosz ngnr63q02 at sneakemail.com
Sat Apr 12 13:29:09 UTC 2014


This works:

main = do
     myargs <- getArgs
     mapM_ (\s -> putStrLn s ) myargs

and imagine that the "body" will be substantial rather than just a putStrLn.  My gut 
instinct is that the code ought to be arranged as:

	<any needed keywords or punctuation> and <the collection of items>
	<body to perform for every element
		...
		...
		>

Meanwhile, there is no need to name the result of getArgs into myargs.

So, getArgs is of type IO [String], and I want to apply that in the manner of a list. 
Without the Monad wrappers, plain
	map ( blah ) strings
could be ( blah ) <$> strings, and in this particular case I don't see a reversed-arg 
version, although there is one for <*> (as <**>).  But, for monad stuff in general there 
are reversed arrows for (most?) everything, and that's where I'm heading.

So the first question is, how do I do the equivalent map-as-nondeterministic-apply when 
the strings is further wrapped in IO, as is the function being applied.

	getArgs >>= mapM_ (\s -> putStrLn s )

does double-duty of moving the argument from last place to the left, as it makes use of 
eta reduction.  Because I have two things going on (list applicative and IO monad) I'm 
losing the slickness of using applicative syntax.  Is there a nice way to make these work 
together?

And more generally, how would you write such a construct?  I'm naturally biased with my 
knowledge in other languages, so maybe there's a completely different "normal" way of 
approaching this?

Thanks,
-John



More information about the Beginners mailing list