It's good to use library features to your advantage.
import Data.List insertAtN ny xs = intercalate [y] . groups n $ xs where groups n xs = takeWhile (not.null) . unfoldr (Just . splitAt n) $ xs
Of course, if you type Char into a list of type [a] , then a will be Char , because in Haskell all the elements of the list are of the same type.
To help you understand this more directly, let's first see how easy it is to make a copy of the list:
copyList (x:xs) = x : copyList xs copyList [] = []
Now imagine that you are adding an index value to each element to be copied (reimplementing zip xs [1..] ):
copyIdxList xs = go 1 xs where go i (x:xs) = (x,i) : go (i+1) xs go _ [] = []
Now that we have the index value, when we deal with each element, we can use it and, say, put every 10th element of the list twice in the result:
copyIdxTenthTwice xs = go 1 xs where go i (x:xs) | i==10 = (x,i) : (x,i) : go 1 xs go i (x:xs) = (x,i) : go (i+1) xs go _ [] = []
See where I am going? Instead of duplicating x you can insert y there. And you do not need to specify indexes in the result.
source share