开发者

give a recursive definition when 'show'ing 'string' elements

开发者 https://www.devze.com 2023-03-09 00:39 出处:网络
I have the following function: convertToStr :: [Int] -> String convertToStr [] = [] convertToStr (int:ints)

I have the following function:

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)))) ++ ", ") ++ ((sh开发者_开发问答ow (head (drop 1 (int:ints)))) ++ ", ")

As can be seen above, I have managed to get the following output from this input:

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

I seem, however to be stuck with regard to being able to write a recursive definition. I'd like to convert a list of any length in [Int] elements to a string with that list and not have it limited as such.


Without explicit recursion you can do it using map and intersperse like this

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

Edit: And with manual recursion it's like

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


First of all, your function is a bit messy. I would suggest you to have a look at some library functions for your task. I suggest intercalate, which takes a list of lists (strings), puts something between them (like ", ") and concats them.

0

精彩评论

暂无评论...
验证码 换一张
取 消