How to add elements to a list every nth round?

281 Views Asked by At

I need to Write a function separate of type int * 'a * 'a list -> 'a lst such that separate (k, x, l) returns the list that inserts element x after each k elements of list l (counting from the end of the list). For example, separate (1, 0, [1,2,3,4]) should return [1,0,2,0,3,0,4] and separate (3, 0, [1,2,3,4]) should return [1,0,2,3,4].

So far, this is what I have, but it is causing an error. Can anyone help me?

fun separate (k: int, x: 'a, l: 'a list) : 'a list =
   let val count:int = k
    in foldr(
        (fn (h, t) =>
            if count = 0
            then count := 1 in
               x::h::t 
            else count = count + 1 : int
                h::t
            )
1

There are 1 best solutions below

0
Igor Drozdov On

Actually the logic is quite right, but it should be implemented by passing changed state into another iteration of foldr due to immutability:

fun separate (k: int, x: 'a, l: 'a list) : 'a list =
  #2 (foldr (fn (h, (count, t)) =>
      if count = 0
      then (k - 1, h::x::t)
      else (count - 1, h::t)
    ) (k, []) l);

Thus, instead of initiating count as a variable, we initiate foldr with tuple (k, []) (where k is the initial value of count and [] is the resulting list) and then decrease the count every step of the iteration.