简体   繁体   中英

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

I've started to learn Haskell and feeling overwhelmed with it. I'm now trying to create a function that either returns a string from standard input or from the contents of a list of files. In other words, I'm trying to replicate the behavior of Unix wc utility which takes input from stdin when no files are given.

I've created something like this:

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

But it doesn't compile since in one case I have [IO String] and in the other IO [String]. I can't make this pattern matching to return IO [String] in all cases. Please point me to right direction.

To make the first pattern also IO [String] , you have to unpack the value from inside the list first and then repack it. Something like this:

do c <- getContents
   return [c]

In normal monadic notation:

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

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

fmap (:[]) getContents

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM