Source

amall / src / am_Array.ml

Full commit
module Array =
  struct
    include Array;

    value map_filter func arr =
      inner [] (Array.length arr - 1)
      where rec inner acc i =
        if i < 0
        then
          Array.of_list acc
        else
          match func arr.(i) with
          [ None -> inner acc (i - 1)
          | Some x -> inner [x :: acc] (i - 1)
          ]
    ;


    value findi_opt pred arr =
      inner 0
      where rec inner i =
        if i = Array.length arr
        then None
        else
          if pred arr.(i)
          then Some (i, arr.(i))
          else inner (i + 1)
    ;


    value eqlen funcname a1 a2 =
      let len = Array.length a1 in
      if len <> Array.length a2
      then invalid_arg ("ExtArray." ^ funcname
        ^ ": arrays must have equal length")
      else
        len
    ;


    value map2 f a1 a2 =
      let len = eqlen "map2" a1 a2 in
      Array.init len
        (fun i -> f a1.(i) a2.(i)
        )
    ;


    value mapi2 f a1 a2 =
      let len = eqlen "mapi2" a1 a2 in
      Array.init len
        (fun i -> f i a1.(i) a2.(i)
        )
    ;


    value iter2 f a1 a2 =
      let len = eqlen "iter2" a1 a2 in
      for i = 0 to len-1
      do
        ( f a1.(i) a2.(i) )
      done
    ;


    value findi_all pred arr =
      inner [] (Array.length arr - 1)
      where rec inner acc i =
        if i < 0
        then acc
        else
          let new_acc =
            if pred arr.(i)
            then [(i, arr.(i)) :: acc]
            else acc
          in
            inner new_acc (i - 1)
    ;


    open Amall_types;

    module Functor
     =
      struct
        type t 'a = array 'a;
        value fmap = Array.map;
      end
    ;

    module Build
     :
      sig
        type t 'a;
        value create : unit -> t 'a;
        value add : 'a -> t 'a -> unit;
        value get : t 'a -> array 'a;
      end
     =
      struct
        open ExtQueue;
        type t 'a = Queue.t 'a;
        value create = Queue.create;
        value add = Queue.push;
        value get = Queue.copy_to_array;
      end
    ;

  end
;