I’m trying to write an intersperse function that takes a list of lists of a
e.g. a list of Strings, and one single a
e.g. a char
as a separator and returns a list of a
or a String.
For example:
intersperse ',' ["a", "b"] -- I will get "a,b"
intersperse ',' ["hello"] -- I will get only "hello"
intersperse ',' ["a", "b", "c"] -- I will get "a,b,c"
intersperse 1 [[2,3,4], [5,6,7]] -- I will get [2, 3, 4, 1, 5, 6, 7]
intersperse 1 [[2,3], [4,5], [6,7]] -- I will get [2, 3, 1, 4, 5, 1, 6, 7]
I wrote the following code, which works fine:
intersperse :: a -> [[a]] -> [a]
intersperse s [] = []
intersperse s (x:[]) = x
intersperse s (x:xs) = loop x xs
where loop a [] = a
loop a (x:xs) = loop (a ++ [s] ++ x) xs
However, when I add a type signature to the loop
function, it won’t compile and I can’t figure out why.