1 (***********************************************************************)
5 (* Jerome Vouillon, projet Cristal, INRIA Rocquencourt *)
6 (* Objective Caml port by John Malecki and Xavier Leroy *)
8 (* Copyright 1996 Institut National de Recherche en Informatique et *)
9 (* en Automatique. All rights reserved. This file is distributed *)
10 (* under the terms of the Q Public License version 1.0. *)
12 (***********************************************************************)
14 (* $Id: primitives.ml 9226 2009-04-02 09:44:21Z xclerc $ *)
16 (*********************** Basic functions and types *********************)
18 (*** Miscellaneous ***)
19 exception Out_of_range
23 (*** Operations on lists. ***)
25 (* Remove an element from a list *)
27 let rec except_e = function
29 | elem::l -> if e = elem then l else elem::except_e l
32 (* Position of an element in a list. Head of list has position 0. *)
34 let rec index_rec i = function
36 | b::l -> if a = b then i else index_rec (i + 1) l
39 (* Return the `n' first elements of `l' *)
41 let rec list_truncate =
43 p0 p1 -> match (p0,p1) with (0, _) -> []
45 | (n, (a::l)) -> a::(list_truncate (n - 1) l)
47 (* Separe the `n' first elements of `l' and the others *)
48 (* ### n list -> (first, last) *)
49 let rec list_truncate2 =
51 p0 p1 -> match (p0,p1) with (0, l) ->
56 let (first, last) = (list_truncate2 (n - 1) l) in
59 (* Replace x by y in list l *)
61 let list_replace x y =
70 (*** Operations on strings. ***)
72 (* Remove blanks (spaces and tabs) at beginning and end of a string. *)
73 let is_space = function
74 | ' ' | '\t' -> true | _ -> false
77 let l = String.length s and i = ref 0 in
79 !i < l && is_space (String.get s !i)
83 let j = ref (l - 1) in
85 !j >= !i && is_space (String.get s !j)
89 String.sub s !i (!j - !i + 1)
91 (* isprefix s1 s2 returns true if s1 is a prefix of s2. *)
94 let l1 = String.length s1 and l2 = String.length s2 in
95 (l1 = l2 && s1 = s2) || (l1 < l2 && s1 = String.sub s2 0 l1)
97 (* Split a string at the given delimiter char *)
99 let split_string sep str =
101 if j >= String.length str then
102 if i >= j then [] else [String.sub str i (j-i)]
103 else if str.[j] = sep then
106 else String.sub str i (j-i) :: skip_sep (j+1)
110 if j < String.length str && str.[j] = sep
115 (*** I/O channels ***)
119 io_out : out_channel;
120 io_fd : Unix.file_descr
123 let io_channel_of_descr fd = {
124 io_in = Unix.in_channel_of_descr fd;
125 io_out = Unix.out_channel_of_descr fd;
129 let close_io io_channel =
130 close_out_noerr io_channel.io_out;
131 close_in_noerr io_channel.io_in;