Create a concatenation function in Haskell: [String] & # 8594; String

I have a lot of problems working with this function:

concatenate :: [String] -> String 

It is intended to simply take a list of strings and return a single string, which is the result of concatenating each element of the list from head to tail. I am trying to stay in map , foldl and foldr functions. I feel like I know that the concept of these functions is good enough, but the most common problem that I am facing is that I have a type conflict. For example, the GHC expects [Char], and I will put in code that seems to be trying to use [[Char]] without knowing it.

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

And I get the following compilation 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 am very new to Haskell, so please laugh. Rigidity is expected and appreciated if it also includes explanations suitable for beginners. Thanks for any help.

+6
source share
1 answer

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

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

And remember that there is already a concat function , which is more general, since it works on any list list (as opposed to just a list of strings).

+9
source

Source: https://habr.com/ru/post/982659/


All Articles