I'm learning Haskell on my own and I'm following the material of a course.
I would like to know if this is idiomatic Haskell.
asList :: [String] -> String asList ss = "[" ++ (concat $ intersperse "," ss) ++ "]"
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It only takes a minute to sign up.Sign up to join this community
It looks idiomatic to me.
There's one slight improvement to the code that I could come up with. There is a function that does what you're doing in the middle, called
intercalate. Here's the definition, from Data.List:
intercalate :: [a] -> [[a]] -> [a] intercalate xs xss = concat (intersperse xs xss)
Using that, your function becomes:
asList :: [String] -> String asList ss = "[" ++ (intercalate "," ss) ++ "]"
++ operator should be used sparingly, and especially avoided after long lists. In this case, the
++ "]" at the end would require walking down nearly the entire constructed string to append the final character.
Here is an implementation that avoids that problem:
asList :: [String] -> String asList ss = '[' : asList' ss where asList' (a:b:ss) = a ++ (',' : asList' (b:ss)) asList' (a:ss) = a ++ asList' (ss) asList'  = "]"