How to create a Haskell function that turns an IO String into an IO [String]?

I began to study Haskell and felt overcrowded. Now I'm trying to create a function that returns a string from standard input or from the contents of a list of files. In other words, I am trying to replicate the behavior of a Unix wc utility that accepts input from stdin when no files are specified.

I created something like this:

parseArgs [] = [getContents] parseArgs fs = mapM readFile fs 

But it does not compile, because in one case I have [IO String] and in the other IO [String]. I cannot make this template suitable for returning IO [String] in all cases. Please point me in the right direction.

+6
io haskell monads
source share
1 answer

To make the first template also IO [String] , first you need to unpack the value from the inside of the list, and then repack it. Something like that:

 do c <- getContents return [c] 

In normal monadic notation:

 getContents >>= \c -> return [c] 

In this case, it is usually better to use a functor instead of a monad. Then you can avoid return :

 fmap (:[]) getContents 

(:[]) has the same meaning as \x -> [x] , it creates a singleton list.

+7
source share

All Articles