## Mercurial > hg > compilers

### comparison lab4/util.ml @ 0:bfdcc3820b32

Find changesets by keywords (author, files, the commit message), revision
number or hash, or revset expression.

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 (* lab4/util.ml *) | |

2 (* Copyright (c) 2017 J. M. Spivey *) | |

3 | |

4 (* |take n [x1; x2; ...] = [x1; x2; ...; xn]| *) | |

5 let rec take n = | |

6 function | |

7 [] -> [] | |

8 | x::xs -> if n = 0 then [] else x :: take (n-1) xs | |

9 | |

10 (* |drop n [x1; x2; ...] = [x_{n+1}; x_{n+2}; ...]| *) | |

11 let rec drop n = | |

12 function | |

13 [] -> [] | |

14 | x::xs -> if n = 0 then x::xs else drop (n-1) xs | |

15 | |

16 (* |can f x| is true if |f x| doesn't raise |Not_found| *) | |

17 let can f x = try f x; true with Not_found -> false | |

18 | |

19 (* |make_hash n [(x1, y1); ...]| creates a hash table of size |n| | |

20 that initially contains the pairs |(x1, y1)|, ... *) | |

21 let make_hash n ps = | |

22 let table = Hashtbl.create n in | |

23 List.iter (function (x, y) -> Hashtbl.add table x y) ps; | |

24 table | |

25 | |

26 (* |accum f [x1; x2; ...; xn] a| computes f xn (... (f x2 (f x1 a)) ...) *) | |

27 let rec accum f ys a = | |

28 match ys with | |

29 [] -> a | |

30 | x::xs -> accum f xs (f x a) |