You cannot mutate variables in OCaml (well, there is a way, but you really shouldn't do simple things like this)
The main trick you can do is to create a helper function that receives additional arguments corresponding to the variables you want to mutate. Notice how I added an additional parameter for i , as well as "mutate" the current head of the list in a similar way.
let rec index_helper (x, vs, i) = match vs with [] -> -1 | (curr::rest) -> if(curr == x) then i else index_helper (x, rest, i+1) ;; let index (x, vs) = index_helper (x, vs, 0) ;;
Such a recursive tail conversion is a way of translating loops into functional programming, but to be honest, it's kind of low level (you have full power, but manual recursion looks like programming with gotos ...).
For some specific patterns that you can try to make, you need to use reusable functions of a higher order, such as a map or folds.
source share