Intersperse fn in Haskell for simple list concat

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.

The issue with the code is that the type signature of the loop function is incorrect. The loop function is supposed to take an accumulator of type [a] and a list of lists of type [[a]], and return a list of type [a]. However, the current type signature of loop is loop :: [a] -> [[a]] -> [a], which is incorrect.

To fix this issue, you need to change the type signature of loop to correctly reflect its parameters and return type. Here is the corrected code:

intersperse :: a -> [[a]] -> [a]
intersperse _ [] = []
intersperse _ (x:[]) = x
intersperse s (x:xs) = loop x xs
  where loop :: [a] -> [[a]] -> [a]
        loop a [] = a
        loop a (y:ys) = loop (a ++ [s] ++ y) ys

With this corrected code, the type signature of the loop function matches its usage, and the code should compile without any issues.