【问题标题】:Trouble with haskell IOhaskell IO的问题
【发布时间】:2017-07-14 19:19:30
【问题描述】:

我很难准确理解 haskell 如何处理输入和输出。例如,这里我试图获取数据文件列表的命令行参数,并将这些文件的内容放入双精度列表列表中。经过一番研究,我最好的实现是:

{- Read Doubles from input, sent them to a list -}
getDoubles :: Handle -> IO [Double]
getDoubles handle = do
        done <- hIsEOF handle
        if done then return []
        else do
                first <- hGetLine handle
                rest <- getDoubles handle
                return (read first : rest)

{- Send the data to the handle -}
sendData :: Handle -> [Double] -> IO()
sendData handle (x:[]) = hPrint handle x
sendData handle (x:xs) = do
        hPrint handle x
        sendData handle xs


main = do
        args <- getArgs 
        handleList <- mapM (\x -> openFile x ReadMode) args
        sendData stdout  (fmap getDoubles handleList)

但这给了我一个错误,因为 getDoubles 返回类型 IO [Double],而不仅仅是 [Double]。 如何将我的 getDoubles 函数映射到我的文件句柄列表上?

【问题讨论】:

  • sendData 采用[Double],但您有一个[Double]s 的集合,每个文件一个。您想如何消除这种不匹配?

标签: haskell io


【解决方案1】:

就像你对openFile 所做的那样(它也做IO),你可以使用mapM

main = do
    args <- getArgs
    handleList <- mapM (\x -> openFile x ReadMode) args
    doubless <- mapM getDoubles handleList
    sendData stdout doubless

你可能还喜欢readFile,如:

parse :: String -> [Double]
parse = map read . lines

main = do
    args <- getArgs
    doubless <- mapM readFile args
    mapM (print . parse) doubless

【讨论】:

  • (这个答案掩盖了sendData :: ... -&gt; [Double] -&gt; ...doubless :: [[Double]] 之间的不匹配。如果约翰回答我对他们问题的评论,我会修复它。)
猜你喜欢
  • 2022-11-14
  • 2016-03-16
  • 2011-07-02
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2020-02-03
  • 2012-03-28
  • 1970-01-01
相关资源
最近更新 更多