Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert specific element y after every n elements in a list

I'm teaching myself Haskell and I've run across the question in my book that ask me to define a function insert that takes a positive integer n, element y, and a list xs that inserts the specified element y after every n elements in the list.

I believe pattern matching would probably be a good way to go but I've yet to really grasp what it means

insert :: Int -> Char -> [a] -> [a]
insert 0 y xs = xs
insert n y [] = []
insert n y (x:xs)

An example of how the function should work:

insert 2 'X' "abcdefghijk" = "abXcdXefXghXijXk"

I've taken care of the base cases at this point but I don't know how to proceed from here.

Any ideas? Thanks

like image 220
NuNu Avatar asked Sep 30 '12 07:09

NuNu


People also ask

How do I add an item to a specific position in a list?

Inserting an element in list at specific index using list. insert() In python list provides a member function insert() i.e. It accepts a position and an element and inserts the element at given position in the list.

How do you add every other number to a string in Python?

You can use sum(mylist[1::2]) to add every odd items. Note: if you are dealing with huge lists or you are already memory constrained you can use itertools. islice instead of plain slicing: sum(islice(mylist, 0, len(mylist), 2)) . This will only take as much memory as one element instead of creating a whole copy.


1 Answers

In the last case, take n elements of the list, insert a singleton list of y and then append the result of recursively calling the function after dropping first n elements of the list.

insert :: Int -> Char -> [a] -> [a]
insert 0 y xs = xs
insert n y [] = []
insert n y xs
 | length xs < n = xs
 | otherwise = take n xs ++ [y] ++ insert n y (drop n xs)
like image 162
Abhinav Sarkar Avatar answered Sep 29 '22 03:09

Abhinav Sarkar