0

I need to convert an list of Char's ex: ["a","b","c"] into a single String ex: "abc"

What I have tried doesn't work - it returns a 'parse error in pattern.' This is my code:

listToString :: [Char] -> String
listToString [] = ""
listToString x:xs = x ++ listToString xs

Thanks for any help!

Greg
  • 1
  • 1
  • 1
  • 3
    `String` is a type alias for `[Char]`. No conversion is needed. `listToString = id` – 4castle May 04 '17 at 00:30
  • Technically, 'x:xs' is a composite pattern that should be put into parentheses: `listToString (x:xs) = ...`. Moreover, on the right side of this equation you try to concatenate a single `Char` and a `String`. Not mentioning that your `listToString` is actually slow `id` defined for strings. – bipll May 04 '17 at 00:38
  • you can use id if you want – Carbon May 04 '17 at 01:05
  • 5
    Some terminology fixes/suggestions to help you learn and search for solutions. 1. You said "an array of Chars" but lists are not arrays. 2 You said "list of Char's ex: `["a","b","c"]` but that's a list of `String`s - a List of Char's would be `['a', 'b', 'c']` which is the same value as `"abc"` since strings are lists of chars. 3. Your parser error is just a lack of parenthesis, try `listToString (x:xs) = ...`. 4. If you want to convert a list of Strings into a single string then use `concat`. – Thomas M. DuBuisson May 04 '17 at 01:55
  • Because of the above mentioned confusions I'm going to vote to close. Feel free to edit the question. Perhaps clarify 1. You are talking about lists not arrays. 2.Are you talking about lists of strings or lists of characters? – Thomas M. DuBuisson May 04 '17 at 01:56

2 Answers2

0

In Haskell, a String is a [Char], so you don't need to convert them.

GHC.Base defines this as:

type  String = [Char]

which is automatically available to you from Prelude (which you don't need to import).

For example:

 ['1','2','3','4'] == "1234"
Alex
  • 8,093
  • 6
  • 49
  • 79
0

As atc correctly mentioned, a String is just a synonym for [Char]

That's why the type of ["a", "b", "c"] is [[Char]], which is the same as [String].

So you can convert a list of Strings with concat:

concat ["a", "b", "c"]

results in

"abc"

If you have a list of Chars, defined like this:

['a', 'b', 'c'] :: [Char] -- (single quotes: Char, double quotes: String)

there is no need to convert as this is the same as

"abc" :: String
Erich
  • 1,838
  • 16
  • 20