1

I'm trying to wrap my head around generics in Haskell. My issue is I created a concatenate function that takes a list of Strings and returns a giant string.

concatenate:: [String] -> String
concatenate xs = foldl (\acc x -> acc ++ x) [] xs

But now I'd like instead of a list of strings, use a list of anything. This can be strings, can be ints. So say

concatenate ["Phil", "is"] 

generates "Philis" while

concatenate [[1,2],[3,4]]

generates [1,2,3,4].

I've found that

concatenate:: [a] -> a
concatenate xs = foldl (\acc x -> acc ++ x) [] xs

does not work and I'm not sure why. Isn't the way haskell works, whatever type a is, the output is a as well? Or is the issue with the second half not allowing it to work as a function for all types?

7
  • When you aren't sure why (and when you ask for help on SO) it is best to read and relay the error message which clearly says there is a type error. Commented May 14, 2013 at 1:37
  • Oh! Sorry about that, the error message reads: Occurs check: cannot construct the infinite type: a0 = [a0] In the first argument of '(++)', namely 'acc' In the expression: acc ++ x In the first argument of 'foldl', namely '(\ acc x -> acc ++ x)' This is after I've replaced [a] with [[a]] with the help of @Pubby 's useful tidbit on String. Is it trying to say that ++ won't work with the type a? Or that it's too general and ++ only works with lists? I'm kind of confused. Commented May 14, 2013 at 1:49
  • With Pubby's fix to the type signature your code is fine. If you are still getting errors then you are using a broken setup or you have made some other change. Did you remember to change the RESULT a to [a] as Pubby pointed out? Commented May 14, 2013 at 1:58
  • 2
    Oh, and just to keep the terminology straight - this is just polymorphism. Generics is a different concept. Commented May 14, 2013 at 2:02
  • Ah! I didn't. I left it as [[a]] -> a. Thanks so much for the catch! Commented May 14, 2013 at 2:03

1 Answer 1

5

Keep in mind that String is an alias for [Char].

What you really intended was this:

concatenate:: [[a]] -> [a]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.