简体   繁体   English

如何创建一个将IO String转换为IO [String]的Haskell函数?

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

I've started to learn Haskell and feeling overwhelmed with it. 我开始学习Haskell并感到不知所措。 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. 换句话说,我正在尝试复制Unix wc实用程序的行为,该实用程序在没有给出文件时从stdin获取输入。

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]. 但是它没有编译,因为在一种情况下我有[IO String]而在另一个IO [String]中。 I can't make this pattern matching to return IO [String] in all cases. 在所有情况下,我无法使此模式匹配以返回IO [String]。 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. 要使第一个模式也是IO [String] ,您必须首先从列表中解压缩值,然后重新打包它。 Something like this: 像这样的东西:

do c <- getContents
   return [c]

In normal monadic notation: 在正常的monadic表示法中:

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

In a case like this, it's usually better to use a functor instead of a monad. 在这种情况下,通常最好使用仿函数而不是monad。 Then you can avoid the return : 然后你可以避免return

fmap (:[]) getContents

(:[]) has the same meaning as \\x -> [x] , it creates a singleton list. (:[])\\x -> [x]具有相同的含义,它创建一个单例列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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