ocaml

OCaml How to reverse only even values in list


I want to transefer something like this:

[0,1,2,3,4,5,6,7]

into

[6,1,4,3,2,5,0,7]

Solution

  • Here's a draft, that reverses the elements at even positions (which is what I assume you meant by your question). This is probably far from optimal (e.g. you should make split and join tail-recursive):

    let rec split = function
      | [] -> [], []
      | h::[] -> [h], []
      | x::y::t -> 
        let a, b = split t in 
        x::a, y::b;;
    
    let rec join a b = match a, b with
      | [], _ -> b
      | _, [] -> a
      | ha::ta, hb::tb -> ha::hb::(join ta tb);;
    
    let doit l = 
      let a, b = split l in 
      join a (List.rev b);;