简体   繁体   English

Haskell Put IO String

[英]Haskell Put IO String

I am trying to read and print the output from the "readProcess" command mapped onto a list of filenames: 我试图读取并打印映射到文件名列表的“readProcess”命令的输出:

files <- readProcess "ls" [] []
let mdList = map ( \file -> do
    md <- readProcess "mdls" [file] []
    return md ) $ splitOn "\n" files in
    map (\md -> putStrLn md) mdList
putStrLn "Complete"

Each time I try to map putStrLn onto the mdList, I get this error: 每次我尝试将putStrLn映射到mdList时,我都会收到此错误:

Couldn't match type ‘IO String’ with ‘[Char]’

I have read many StackOverflow answers that seem to just use putStrLn on an IO String but I am unable to do so. 我已经阅读了许多StackOverflow答案,似乎只是在IO字符串上使用putStrLn但我无法这样做。 Also, I am new to Haskell so any other tips are also appreciated. 此外,我是Haskell的新手,所以任何其他提示也值得赞赏。

You are using 您正在使用

map :: (a -> b) -> [a] -> [b]

which specializes to 哪个专攻

map :: (a -> IO b) -> [a] -> [IO b]

The final result, [IO b] is not what we need. 最终结果, [IO b]不是我们需要的。 That is a list of IO actions, ie the equivalent of a list of non-executed no-arguments imperative functions. 这是一个IO动作列表,即相当于一个未执行的无参数命令功能列表。 Instead, we want a single IO action, whose result is a list of b : that would be IO [b] instead of [IO b] . 相反,我们需要一个单独的 IO操作,其结果是b的列表: IO [b]而不是[IO b]

The library provides that as well: 图书馆也提供了:

mapM :: (a -> IO b) -> [a] -> IO [b]

or, if we don't care about collecting the results 或者,如果我们不关心收集结果

mapM_ :: (a -> IO b) -> [a] -> IO ()

The library also provides variants with flipped arguments: 该库还提供带有翻转参数的变体:

for  :: [a] -> (a -> IO b) -> IO [b]
for_ :: [a] -> (a -> IO b) -> IO ()

So, the original code can be fixed as follows: 因此,原始代码可以修复如下:

import Data.Foldable

files <- readProcess "ls" [] []
for_ files $ \file -> do
    md <- readProcess "mdls" [file] []
    putStrLn md
putStrLn "Complete"

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

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