List reversing in Ocaml

六月ゝ 毕业季﹏ 提交于 2019-11-28 10:10:40

问题


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.

For example:

Function([[1;2;3] ; [2;3] ; [1;2;3] ; [5;6;7]])

returns:

([[3;2;1] ; [2;3] ; [3;2;1] ; [5;6;7]])

I already created a function that reverse a single list:

let rev =
  let rec rev_append acc l =
    match l with
      [] -> acc
    | h::t -> rev_append (h::acc) t in
  fun l -> rev_append [] l;;

But now i am stuck.


回答1:


let rev_list l =
  let rec rev_acc acc = function
    | [] -> acc
    | hd::tl -> rev_acc (hd::acc) tl
  in 
  rev_acc [] l

let rev_even l = 
  let rec rev i acc = function
    | [] -> rev_list acc
    | hd::tl ->
      if i mod 2 = 0 then rev (i+1) ((rev_list hd)::acc) tl
      else rev (i+1) (hd::acc) tl
  in 
  rev 0 [] l

note that they are all tail-recursive

edit

A suggestion to Noran:

tail-recursive is quite important in functional programming and OCaml. Please bear in mind.




回答2:


let rec todo l = let rec aux r = function
       | [] -> []
       | h::t -> (if r then h else rev h)::(aux (not r) t)
in aux true l;;



回答3:


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]]  


来源:https://stackoverflow.com/questions/21286668/list-reversing-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!