Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create concatenate function in Haskell: [String] -> String

I'm having a lot of trouble getting this function to work:

concatenate :: [String] -> String

It is designed to simply take a list of strings and return a single string that is the result of the concatenations of each element of the list from head to tail. I'm trying to stay within the map, foldl, and foldr functions. I feel like I know what the concept of these functions do well enough, but the most common problem I'm running into is that I'm having a conflict of types. GHC will expect a [Char] for example, and I'll put in code that is apparently trying to use a [[Char]] without me knowing it.

For example: concatenate (x:xs) = foldr (++) x (concatenate xs)

And I get the following compile error:

Couldn't match type `Char' with `[Char]'
Expected type: [[Char]]
  Actual type: String
In the return type of a call of `concatenate'
In the third argument of `foldr', namely `(concatenate xs)'
In the expression: foldr (++) x (concatenate xs)

I'm very new to Haskell, so please feel free to laugh. Harshness is expected, and welcomed, as long as an explanation fit for a newbie is also included. Thank you for any and all help.

like image 781
UnworthyToast Avatar asked Feb 18 '15 03:02

UnworthyToast


People also ask

How do I combine two strings in Haskell?

The ++ function takes two lists and joins them together. A string is just a list of characters.

How do I concatenate strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

How do I concatenate a string to a Char?

The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function. In the above example, we have declared two char arrays mainly str1 and str2 of size 100 characters.

How does ++ work in Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list. So if you have the list [x] and the list [y] then you can concatenate them like this: [x]++[y] to get [x, y ]. Notice that : takes an element and a list while ++ takes two lists.


1 Answers

You actually don't need the recursive call there. The function foldr already simulates a recursive call. All you need to do is use:

concatenate :: [String] -> String
concatenate ls = foldr (++) "" ls

And remember that there's a concat function already, which is more generic, as it works on any list of list (as opposed to simply list of strings).

like image 167
Shoe Avatar answered Sep 21 '22 17:09

Shoe