Replicate items from list basing on the second list

Write a function that replicates items in a list based on a second list specifying the number of times items are to be duplicated.

Write the function in Ocaml in a functional way of programming using lists.

If library functions - may be used only with O(1) computational complexity.

For example:

duplicate [5;6;7] [0;2;5;3];;



My code so far:

let duplicate (list1, list2)=
let rec read (list2, list1) = 
if List.hd list2 = 0 then read ( list2, list1) else print (List.hd list2, List.hd list1)
let rec print (acc, num) =
num :: (print (acc-1, num));;

First of all, it does not compile, I have “syntax error”…
I do not feel sure about these “nested” functions.
I believe that complexity could be better.

Hi. The issue with your nested functions is that you forgot the in keyword. When defining nested functions, you need to show to the compiler that you are still writing the body of the duplicate function, and not defining read or print as brand new functions. Here is a toy example :

let dbl_and_dup x =
  let dbl x = x * 2 in
  let dup x = (x, x) in
  dup (dbl x)

As you can see, dbl and dup are nested functions, and thus are invisible from outside the dbl_and_dup function.

Here is an stdlib version of what you asked, for two lists of same length :

let dup l1 l2 =
  List.combine l1 l2
  |> (fun (e, n) -> List.init n (fun _ -> e))
  |> List.concat

A little additional work is required for the function to accept two lists of different lengths. And if you do not want to use library functions, you can define them yourself. Hope it helps !

Not sure, but your stdlib version returns error: Unbound value List.init

You might have an old stdlib. List.init was added in 4.06.