insert :: Eq(a) => a -> a -> [a] -> [a]
insert m n [] = []
insert m n (x:xs) | m==x = n : x : insert m n xs
| otherwise = x : insert m n x
Since you will only be adding values to the front of the list, your insert
function is unnecessary. (:)
will suffice instead. Much like in insert
, we pass recursively over the list. Since we want to check if two values match at a time and will also call the function recursively on different lists based on whether or not we find a match, it's a good idea to pattern match (x1:x2:xs)
rather than just (x:xs)
.
If m
matches x1
and q
matches x2
, we place the onto the head of the list and call interspace
recursively on the rest of the list. If they do not mach, we call interspace
on (x2:xs)
.
interspace :: Eq a => a -> a -> a-> [a] -> [a]
interspace m n q [] = []
interspace m n q [x] = [x]
interspace m n q (x1:x2:xs) | m == x1 && q == x2 = m : n : q : interspace m n q xs
| otherwise = x1 : interspace m n q (x2:xs)
Example usage:
ghci>> interspace 1 2 1 [1,1,2,1,1]
[1,2,1,2,1,2,1]
ghci>> interspace 1 2 1 [1,1,3]
[1,2,1,3]
ghci>> interspace 1 2 1 [1,2,4,2]
[1,2,4,2]
ghci>> interspace 1 2 1 [1]
[1]
ghci>> interspace 1 2 1 []
[]