开发者

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]
parse开发者_如何转开发Args 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜