[Haskell-cafe] One liner?

Mitchell, Neil neil.mitchell.2 at credit-suisse.com
Thu Oct 2 11:26:23 EDT 2008


Hi
 
You can translate this step by step.
 
main = do dc <- getDirectoryContents "./foo/"
          mapM_ putStrLn dc

Translating out the do notation
(http://www.haskell.org/haskellwiki/Keywords#do):

main = getDirectoryContents >>= \dc ->
       mapM_ putStrLn dc

Then we can chop out the dc argument, as its \x -> .... x, and can be
removed (eta reduction):

main = getDirectoryContents >>= 
       mapM_ putStrLn

And finally we just remove the newline:

main = getDirectoryContents >>= mapM_ putStrLn  

Alternatively, we can flip the >>= for =<< and write:

main = mapM_ putStrLn =<< getDirectoryContents

This is now one line, and mirrors how you would write the function if it
was pure using function composition.

Thanks

Neil
 

This material is sales and trading commentary and does not constitute
investment research. Please follow the attached hyperlink to an
important disclaimer 
<www.credit-suisse.com/emea/legal
<outbind://31/www.credit-suisse.com/emea/legal> > 

 


________________________________

	From: haskell-cafe-bounces at haskell.org
[mailto:haskell-cafe-bounces at haskell.org] On Behalf Of Paul Keir
	Sent: 02 October 2008 4:20 pm
	To: haskell-cafe at haskell.org
	Subject: [Haskell-cafe] One liner?
	
	

	Hi all,
	
	There's a common little situation I keep bumping up against. I
don't understand where I'm going wrong, so I've made a little example.
It's to do with binding a result to a variable name using "<-". This
code works fine:
	
	----------------------------------------------
	module Main where
	
	import System.Directory (getDirectoryContents)
	
	main = do dc <- getDirectoryContents "./foo/"
	          mapM_ putStrLn dc
	----------------------------------------------
	
	But if I try to avoid the use of the bind to "dc", I fail:
	
	----------------------------------------------
	mapM_ putStrLn (getDirectoryContents "./foo/")
	----------------------------------------------
	
	I've tried using map instead of mapM_, and inserted "return"s
here and there, but no luck. Can anyone tell me where and why I'm going
wrong? The error message is below.
	
	Cheers,
	Paul
	
	
	Couldn't match expected type `[String]'
	       against inferred type `IO [FilePath]'
	In the second argument of `mapM_', namely
	    `(getDirectoryContents "./foo/")'
	In the expression: mapM_ putStrLn (getDirectoryContents
"./foo/")
	In the definition of `main':
	    main = mapM_ putStrLn (getDirectoryContents "./foo/")
	


==============================================================================
Please access the attached hyperlink for an important electronic communications disclaimer: 

http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html
==============================================================================



More information about the Haskell-Cafe mailing list