如何在Haskell中打印目录内容

2ledvvac  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(116)

我正在使用getDirectoryContents沿着toText派生和fldmap。
发生错误是:

IoString.hs:17:5: error:
    • Couldn't match expected type: FilePath -> IO ()
                  with actual type: IO b0
    • In a stmt of a 'do' block:
        contents <- getDirectoryContents "/home/lukas"
      In the expression:
        do contents <- getDirectoryContents "/home/lukas"
           contents >>= map print toText
      In an equation for ‘main’:
          main
            = do contents <- getDirectoryContents "/home/lukas"
                 contents >>= map print toText
   |
17 |     contents <- getDirectoryContents "/home/lukas"
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

还有更多的人在下面。
在附件中,代码:

--{-# LANGUAGE OverloadedStrings #-}

module Main where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Text (pack, Text)
import System.Directory (getDirectoryContents, getCurrentDirectory, makeAbsolute)
import GHC.Real (reduce)

parse xs = foldMap pack

toText :: [FilePath] -> Text
toText = foldMap pack

main :: FilePath -> IO ()
main = do
    contents <- getDirectoryContents "/home/lukas"
    contents >>= map print toText

尝试读取目录内容,期望打印。

m0rkklqb

m0rkklqb1#

一个基本的命令式for循环:

import Data.Foldable (for_)

main :: IO ()
main = do
    contents <- getDirectoryContents "/home/lukas"
    for_ contents $ \f -> do -- "do" not really needed if the body is one line
        print f

这可以通过多种方式缩短,例如:

import Data.Foldable (traverse_)

main :: IO ()
main = do
    contents <- getDirectoryContents "/home/lukas"
    traverse_ print contents

-- or

main :: IO ()
main =
    getDirectoryContents "/home/lukas" >>= traverse_ print

traverse_for_是相同的函数,但它们的参数颠倒了。

相关问题