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