当“显示”“字符串”元素时给出递归定义

问题描述

|| 我有以下功能
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]
个元素中任意长度的列表转换为带有该列表的字符串,而不是仅限于此。     

解决方法

        没有显式递归,您可以使用
map
并像这样散布
convertToString :: [Int] -> String
convertToString = concat . (intersperse \",\") . map show
编辑:手动递归就像
cts [] = \"\"
cts (x:xs)
   | null xs = show x 
   | otherwise = show x ++ \",\" ++ cts xs
    ,        首先,您的功能有点混乱。我建议您看一下一些用于您的任务的库函数。我建议
intercalate
,它使用列表(字符串)的列表,在它们之间放一些东西(如
\",\"
),然后将它们连接起来。