在'show'ing'string'元素时给出一个递归定义

时间:2011-05-30 10:37:18

标签: string list haskell

我有以下功能:

convertToStr :: [Int] -> String
convertToStr [] = []
convertToStr (int:ints)
    | length (int:ints) == 1 = ((show (head (drop 0 (int:ints)))) ++ ", ")
    | length (int:ints) == 2 = ((show (head (drop 0 (int:ints)))) ++ ", ") ++ ((show (head (drop 1 (int:ints)))) ++ ", ")

如上所示,我已设法从此输入获得以下输出:

> convertToStr [3,5]
"3, 5, "

我似乎对于能够编写递归定义感到困惑。我想将[Int]元素中任意长度的列表转换为包含该列表的字符串,而不是限制它。

2 个答案:

答案 0 :(得分:5)

如果没有明确的递归,您可以使用mapintersperse这样做

convertToString :: [Int] -> String
convertToString = concat . (intersperse ", ") . map show

编辑:手动递归就像

cts [] = ""
cts (x:xs)
   | null xs = show x 
   | otherwise = show x ++ ", " ++ cts xs

答案 1 :(得分:0)

首先,你的功能有点乱。我建议你看看你的任务的一些库函数。我建议intercalate,它取一个列表(字符串)列表,在它们之间放置一些东西(比如", ")并连接它们。