7

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.

1 Answer 1

12

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).

Sign up to request clarification or add additional context in comments.

1 Comment

And it was that simple... Thank you. It's pretty difficult for me to get into the mindset required for developing functions in Haskell after coming right from C. And about concat, I know it exists, but I'm trying to understand these basic functions by making my own versions. It's seemed to help in other languages in the past.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.