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