Search code examples
recursionfunctional-programmingocaml

Function calling for each element in a list


Using only recursion (ie. no loops of any sort), given a list of elements, how can I call a function each time for every element of the list using that element as an argument each time in OCaml? Fold and map would not work because although they are applying a function to each element, it returns a list of whatever function I called on each element, which is not what I want.

To better illustrate what I'm essentially trying to do in OCaml, here's the idea of what I want in Ruby code:

arr.each {|x| some_function x}

but I must do this using only recursion and no iter functions


Solution

  • The correct recursive function is described as:

    • if the list is empty, do nothing;
    • else, process the first element and then the tail of the list.

    The corresponding code is:

    let rec do_all f lst =
    match lst with
    | [] -> ()
    | x :: xs -> f x; do_all f xs