ocaml/stdlib/stack.ml

43 lines
1.4 KiB
OCaml
Raw Normal View History

(***********************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. All rights reserved. This file is distributed *)
(* under the terms of the GNU Library General Public License, with *)
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
2015-11-22 12:15:03 -08:00
type 'a t = { mutable c : 'a list; mutable len : int; }
exception Empty
2015-11-22 12:15:03 -08:00
let create () = { c = []; len = 0; }
2015-11-22 12:15:03 -08:00
let clear s = s.c <- []; s.len <- 0
2015-11-22 12:15:03 -08:00
let copy s = { c = s.c; len = s.len; }
2015-11-22 12:15:03 -08:00
let push x s = s.c <- x :: s.c; s.len <- s.len + 1
let pop s =
match s.c with
2015-11-22 12:15:03 -08:00
| hd::tl -> s.c <- tl; s.len <- s.len - 1; hd
| [] -> raise Empty
let top s =
match s.c with
2015-11-22 12:15:03 -08:00
| hd::_ -> hd
| [] -> raise Empty
let is_empty s = (s.c = [])
2015-11-22 12:15:03 -08:00
let length s = s.len
let iter f s = List.iter f s.c
2015-06-09 05:52:40 -07:00
let fold f acc s = List.fold_left f acc s.c