Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Haskell中编写到文件的递归实现_Haskell_Io - Fatal编程技术网

在Haskell中编写到文件的递归实现

在Haskell中编写到文件的递归实现,haskell,io,Haskell,Io,我试图创建一个方法,给定要写入的文件名和字符串列表,将该列表的内容写入文件,每次写入3个字符串 e、 g 到目前为止,我有: toFile :: String -> [String] -> IO () toFile s [] = appendFile s "" toFile s (x:y:z:xs) = appendFile s (x ++ " " ++ y ++ " " ++ z ++ "\n") 但我不知道如何在IO中应用递归性。。。任何帮助都将不胜感激 提前感谢。首先想象一下

我试图创建一个方法,给定要写入的文件名和字符串列表,将该列表的内容写入文件,每次写入3个字符串

e、 g

到目前为止,我有:

toFile :: String -> [String] -> IO ()
toFile s [] = appendFile s ""
toFile s (x:y:z:xs) = appendFile s (x ++ " " ++ y ++ " " ++ z ++ "\n")
但我不知道如何在IO中应用递归性。。。任何帮助都将不胜感激


提前感谢。

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

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)
如果需要,可以内联和GroupString的定义,以查看发生了什么:

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
import Data.List (intercalate)
import Data.List.Split (chunksOf)
toFile s = mapM_ (\x -> appendFile s $ intercalate " " x ++ "\n") . chunksOf 3