List reversing in Ocaml

前端 未结 3 694
悲哀的现实
悲哀的现实 2020-12-21 16:35

How to reverse even sublists of a list if we assume that we count elements from 0. I want the solution to be \"manually-coded\". I\'ve got a big problem with this task.

3条回答
  •  甜味超标
    2020-12-21 17:31

    For fun, I've done a stuff like this,

    let rev_at_even_idx list = 
      let s0, s1 = ([], 0), [] in
      let aux0 (a, i) x = 
        (x, i mod 2) :: a, succ i 
      in
      let aux1 a = function 
        | l, 0 -> List.rev l :: a 
        | l, _ -> l :: a 
      in 
      List.fold_left aux1 s1 
      @@ fst @@ 
      List.fold_left aux0 s0 list
    ;;
    
    rev_at_even_idx [[1;2;3] ; [2;3] ; [1;2;3] ; [5;6;7]];;  
    - : int list list = [[3; 2; 1]; [2; 3]; [3; 2; 1]; [5; 6; 7]]  
    

提交回复
热议问题