comparison ppc/util.ml @ 0:bfdcc3820b32

Basis
author Mike Spivey <mike@cs.ox.ac.uk>
date Thu, 05 Oct 2017 08:04:15 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:bfdcc3820b32
1 (* ppc/util.ml *)
2 (* Copyright (c) 2017 J. M. Spivey *)
3
4 (* |copy n x = [x; x; ...; x]| with |n| copies of |x| *)
5 let rec copy n x = if n <= 0 then [] else x :: copy (n-1) x
6
7 (* |take n [x1; x2; ...] = [x1; x2; ...; xn]| *)
8 let rec take n =
9 function
10 [] -> []
11 | x::xs -> if n = 0 then [] else x :: take (n-1) xs
12
13 (* |drop n [x1; x2; ...] = [x_{n+1}; x_{n+2}; ...]| *)
14 let rec drop n =
15 function
16 [] -> []
17 | x::xs -> if n = 0 then x::xs else drop (n-1) xs
18
19 (* |can f x| is true if |f x| doesn't raise |Not_found| *)
20 let can f x = try f x; true with Not_found -> false
21
22 (* |make_hash n [(x1, y1); ...]| creates a hash table of size |n|
23 that initially contains the pairs |(x1, y1)|, ... *)
24 let make_hash n ps =
25 let table = Hashtbl.create n in
26 List.iter (function (x, y) -> Hashtbl.add table x y) ps;
27 table
28
29 (* |accum f [x1; x2; ...; xn] a| computes f xn (... (f x2 (f x1 a)) ...) *)
30 let rec accum f ys a =
31 match ys with
32 [] -> a
33 | x::xs -> accum f xs (f x a)