17152
|
1 |
(* Title: Pure/General/alist.ML
|
|
2 |
ID: $Id$
|
|
3 |
Author: Florian Haftmann, TU Muenchen
|
|
4 |
|
|
5 |
Association lists -- lists of (key, value) pairs with unique keys.
|
|
6 |
A light-weight representation of finite mappings;
|
|
7 |
see also Pure/General/table.ML for a more scalable implementation.
|
|
8 |
*)
|
|
9 |
|
|
10 |
signature ALIST =
|
|
11 |
sig
|
|
12 |
val lookup: ('a * 'b -> bool) -> ('b * 'c) list -> 'a -> 'c option
|
|
13 |
val defined: ('a * 'b -> bool) -> ('b * 'c) list -> 'a -> bool
|
|
14 |
val update: ('a * 'a -> bool) -> ('a * 'b)
|
|
15 |
-> ('a * 'b) list -> ('a * 'b) list
|
|
16 |
val default: ('a * 'a -> bool) -> ('a * 'b)
|
|
17 |
-> ('a * 'b) list -> ('a * 'b) list
|
|
18 |
val delete: ('a * 'b -> bool) -> 'a
|
|
19 |
-> ('b * 'c) list -> ('b * 'c) list
|
|
20 |
val map_entry: ('a * 'b -> bool) -> 'a -> ('c -> 'c)
|
|
21 |
-> ('b * 'c) list -> ('b * 'c) list
|
17487
|
22 |
val make: ('a -> 'b) -> 'a list -> ('a * 'b) list
|
17497
|
23 |
val find: ('a * 'b -> bool) -> ('c * 'b) list -> 'a -> 'c list
|
17152
|
24 |
end;
|
|
25 |
|
|
26 |
structure AList: ALIST =
|
|
27 |
struct
|
|
28 |
|
|
29 |
fun lookup _ [] _ = NONE
|
|
30 |
| lookup eq ((key, value)::xs) key' =
|
|
31 |
if eq (key', key) then SOME value
|
|
32 |
else lookup eq xs key';
|
|
33 |
|
|
34 |
fun defined _ [] _ = false
|
|
35 |
| defined eq ((key, value)::xs) key' =
|
|
36 |
eq (key', key) orelse defined eq xs key';
|
|
37 |
|
|
38 |
fun update eq (key, value) xs =
|
|
39 |
let
|
|
40 |
fun upd ((x as (key', _))::xs) =
|
|
41 |
if eq (key, key')
|
|
42 |
then (key, value)::xs
|
|
43 |
else x :: upd xs
|
|
44 |
in if defined eq xs key then upd xs else (key, value)::xs end;
|
|
45 |
|
|
46 |
fun default eq (key, value) xs =
|
|
47 |
if defined eq xs key then xs else (key, value)::xs;
|
|
48 |
|
|
49 |
fun delete eq key xs =
|
|
50 |
let
|
|
51 |
fun del ((x as (key', _))::xs) =
|
|
52 |
if eq (key, key') then xs
|
|
53 |
else x :: del xs;
|
|
54 |
in if defined eq xs key then del xs else xs end;
|
|
55 |
|
17191
|
56 |
fun map_entry eq key' f xs =
|
|
57 |
let
|
|
58 |
fun mapp ((x as (key, value))::xs) =
|
|
59 |
if eq (key', key) then (key, f value)::xs
|
|
60 |
else x :: mapp xs
|
|
61 |
in if defined eq xs key' then mapp xs else xs end;
|
|
62 |
|
17487
|
63 |
fun make keyfun =
|
|
64 |
let fun keypair x = (x, keyfun x)
|
|
65 |
in map keypair end;
|
|
66 |
|
17497
|
67 |
fun find eq [] _ = []
|
|
68 |
| find eq ((key, value) :: xs) value' =
|
|
69 |
let
|
|
70 |
val values = find eq xs value'
|
|
71 |
in if eq (value', value) then key :: values else values end;
|
|
72 |
|
17152
|
73 |
end;
|