Skip to content

OCaml examples for the paper

Kiran Gopinathan edited this page Jun 21, 2022 · 3 revisions
  1. Seq to array:
let to_array (l: ('a t[@collection Common.of_list])) =
  match l() with
  | Nil -> 
    [| |]
  | Cons ((x: 'a), (_tl: 'a t)) ->
    let (n : int) = length' l in
    let (a : 'a array) = Array.make n x in
    let _ = iteri
      (fun (i: int) (x: 'a) -> a.(i) <- x)
      l in
    a
let to_array (s: ('a t[@collection Common.of_list])) =
  let ((len: int), (ls: 'a list))[@rewrite list_fold_length_rev] =
    fold (fun ((i: int), (acc: 'a list)) (x: 'a) -> (i + 1, x :: acc)) (0, []) s in
   match ls with
     | [] -> (* 2 *) [| |]
     | (init: 'a)::(rest: 'a list) ->
       let (a: 'a array) = Array.make len init in
       let (idx: int) = len - 2 in
       let _ = List.fold_left (fun (i: int) (x: 'a) -> a.(i) <- x; i - 1) idx rest in
       a
  1. Seq to array (2)
let to_array (s: ('a t[@collection Common.of_list])) =
  let ((len: int), (ls: 'a list))[@rewrite list_fold_length_rev] =
    fold (fun ((i: int), (acc: 'a list)) (x: 'a) -> (i + 1, x :: acc)) (0, []) s in
   match ls with
     | [] -> (* 2 *) [| |]
     | (init: 'a)::(rest: 'a list) ->
       let (a: 'a array) = Array.make len init in
       let (idx: int) = len - 2 in
       let _ = List.fold_left (fun (i: int) (x: 'a) -> a.(i) <- x; i - 1) idx rest in
       a
let to_array l =
  let len = ref 0 in
  let ls = fold_left (fun acc x -> incr len;  x :: acc) [] l in
  match ls with
    | [] -> [||]
    | init::rest ->
      let a = Array.make !len init in
      let idx = !len - 2 in
      ignore (List.fold_left (fun i x -> a.(i) <- x; i - 1) idx rest : int);
      a
  1. RAL of list:
let of_list s =
  let l = ref empty in
  List.iter (fun x -> l := cons x !l) s;
  rev !l
let of_list s =
  let l = List.fold_left (fun l x -> cons x l) empty s in
  rev l