Skip to content
This repository
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 71 lines (50 sloc) 1.912 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
open Common

(*****************************************************************************)
(* Collection *)
(*****************************************************************************)

(*---------------------------------------------------------------------------*)
type ('a, 'b) view = Empty | Cons of 'a * 'b

class virtual ['a] ocollection =
object(o: 'o)
  inherit Objet.objet

  method virtual empty: 'o
  method virtual add: 'a -> 'o

  method virtual iter: ('a -> unit) -> unit
  method virtual view: ('a, 'o) view

  (* no need virtual, but better to redefine for efficiency *)
  method virtual del: 'a -> 'o (* can do default with: view+iter *)
  method virtual mem: 'a -> bool (* can do default with: mem(tolist) *)
  method virtual null: bool (* can do default with: lenght(tolist)= 0 *)


  method add2: 'a -> unit = fun a ->
    o#add a +> ignore;
    ()
  method del2: 'a -> unit = fun a ->
    o#del a +> ignore;
    ()
  method clear: unit =
    o#iter (fun e -> o#del2 e);
    



  method fold: 'b. ('b -> 'a -> 'b) -> 'b -> 'b = fun f a ->
    let a = ref a in
    o#iter (fun e -> a := f !a e);
    !a

  method tolist: 'a list =
    List.rev (o#fold (fun acc e -> e::acc) [])
  method fromlist: 'a list -> 'o =
    fun xs -> xs +> List.fold_left (fun o e -> o#add e) o#empty

  method length: int =
    (* oldsimple: o#tolist +> List.length *)
    (* opti: *)
    let count = ref 0 in
    o#iter (fun e -> incr count);
    !count

  method exists: ('a -> bool) -> bool = fun f ->
    o#tolist +> List.exists f

  method filter: ('a -> bool) -> 'o = fun f ->
    (* iter and call add from empty, or del *)
    o#tolist +> List.filter f +> o#fromlist

  (* forall, fold, map *)

  method getone: 'a =
    match o#view with Cons (e,tl) -> e | Empty -> failwith "no head"
  method others: 'o =
    match o#view with Cons (e,tl) -> tl | Empty -> failwith "no tail"

end

Something went wrong with that request. Please try again.