【问题标题】:Writing to file recursive implementation in Haskell在 Haskell 中写入文件递归实现
【发布时间】:2014-12-13 00:10:34
【问题描述】:

我正在尝试创建一个方法,在给定要写入的文件名和字符串列表的情况下,一次将 3 个字符串写入该列表的内容。

例如

James Philipp Francis
Carl Tom Matt
Audrey Adam Patrick

到目前为止,我有这个:

toFile :: String -> [String] -> IO ()
toFile s [] = appendFile s ""
toFile s (x:y:z:xs) = appendFile s (x ++ " " ++ y ++ " " ++ z ++ "\n")

但我不知道如何在 IO 中应用递归...任何帮助将不胜感激。

提前致谢。

【问题讨论】:

    标签: haskell io


    【解决方案1】:

    首先想象一下,如果你要返回一个列表,你会怎么做。我认为它应该看起来很简单。

    groupStrings :: [String] -> [String]
    groupStrings [] = [] 
    groupStrings (x:y:z:r) = (x ++ " " ++ y ++ " " ++ z ++ "\n") : groupStrings r
    

    请注意,此模式并非详尽无遗:您必须处理列表包含 1 个或 2 个元素的情况。最简单的方法是添加更多案例:

    groupStrings :: [String] -> [String]
    groupStrings [] = [] 
    groupStrings [x] = x ++ "\n"
    groupStrings [x,y] = x ++ " " ++ y ++ "\n"
    groupStrings (x:y:z:r) = (x ++ " " ++ y ++ " " ++ z ++ "\n") : groupStrings r
    

    那么你的功能就是

    toFile :: String -> [String] -> IO ()
    toFile s xs = mapM_ (appendFile s) (groupStrings xs)
    

    如果需要,可以内联mapM_groupStrings 的定义,看看发生了什么:

    toFile :: String -> [String] -> IO ()
    toFile s [] = return () -- appendFile s "" does nothing
    toFile s [x] = appendFile s $ x ++ "\n"
    toFile s [x,y] = appendFile s $ x ++ " " ++ y ++ "\n"
    toFile s (x:y:z:r) = do 
      appendFile s (x ++ " " ++ y ++ " " ++ z ++ "\n")
      toFile s $ groupStrings r
    

    你也可以把这个写得很好:

    import Data.List (intercalate)
    import Data.List.Split (chunksOf)
    toFile s = mapM_ (\x -> appendFile s $ intercalate " " x ++ "\n") . chunksOf 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多