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
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With