2014-12-13 59 views
2

我想创建一个方法,给定要写入的文件的名称和字符串列表,写入文件列表中的内容,一次3个字符串。在Haskell中写入文件递归实现

例如

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应用递归性...任何帮助,将不胜感激。

在此先感谢。

回答

4

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

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