## Mercurial > hg > compilers

### annotate ppc/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 |

rev | line source |
---|---|

mike@0 | 1 (* ppc/util.ml *) |

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

mike@0 | 3 |

mike@0 | 4 (* |copy n x = [x; x; ...; x]| with |n| copies of |x| *) |

mike@0 | 5 let rec copy n x = if n <= 0 then [] else x :: copy (n-1) x |

mike@0 | 6 |

mike@0 | 7 (* |take n [x1; x2; ...] = [x1; x2; ...; xn]| *) |

mike@0 | 8 let rec take n = |

mike@0 | 9 function |

mike@0 | 10 [] -> [] |

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

mike@0 | 12 |

mike@0 | 13 (* |drop n [x1; x2; ...] = [x_{n+1}; x_{n+2}; ...]| *) |

mike@0 | 14 let rec drop n = |

mike@0 | 15 function |

mike@0 | 16 [] -> [] |

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

mike@0 | 18 |

mike@0 | 19 (* |can f x| is true if |f x| doesn't raise |Not_found| *) |

mike@0 | 20 let can f x = try f x; true with Not_found -> false |

mike@0 | 21 |

mike@0 | 22 (* |make_hash n [(x1, y1); ...]| creates a hash table of size |n| |

mike@0 | 23 that initially contains the pairs |(x1, y1)|, ... *) |

mike@0 | 24 let make_hash n ps = |

mike@0 | 25 let table = Hashtbl.create n in |

mike@0 | 26 List.iter (function (x, y) -> Hashtbl.add table x y) ps; |

mike@0 | 27 table |

mike@0 | 28 |

mike@0 | 29 (* |accum f [x1; x2; ...; xn] a| computes f xn (... (f x2 (f x1 a)) ...) *) |

mike@0 | 30 let rec accum f ys a = |

mike@0 | 31 match ys with |

mike@0 | 32 [] -> a |

mike@0 | 33 | x::xs -> accum f xs (f x a) |