author | haftmann |
Mon, 16 Feb 2009 19:11:55 +0100 | |
changeset 29940 | 83b373f61d41 |
parent 29368 | 503ce3f8f092 |
child 32094 | 89b9210c7506 |
permissions | -rw-r--r-- |
28199 | 1 |
(* Title: Pure/Concurrent/par_list.ML |
2 |
Author: Makarius |
|
3 |
||
4 |
Parallel list combinators. |
|
5 |
||
6 |
Notes: |
|
7 |
||
8 |
* These combinators only make sense if the operator (function or |
|
9 |
predicate) applied to the list of operands takes considerable |
|
10 |
time. The overhead of scheduling is significantly higher than |
|
11 |
just traversing the list of operands sequentially. |
|
12 |
||
28358 | 13 |
* The order of operator application is non-deterministic. Watch out |
28199 | 14 |
for operators that have side-effects or raise exceptions! |
15 |
*) |
|
16 |
||
17 |
signature PAR_LIST = |
|
18 |
sig |
|
19 |
val map: ('a -> 'b) -> 'a list -> 'b list |
|
20 |
val get_some: ('a -> 'b option) -> 'a list -> 'b option |
|
21 |
val find_some: ('a -> bool) -> 'a list -> 'a option |
|
22 |
val exists: ('a -> bool) -> 'a list -> bool |
|
23 |
val forall: ('a -> bool) -> 'a list -> bool |
|
24 |
end; |
|
25 |
||
29368 | 26 |
structure Par_List: PAR_LIST = |
28199 | 27 |
struct |
28 |
||
29 |
fun raw_map f xs = |
|
28645 | 30 |
if Future.enabled () then |
28549 | 31 |
let |
29120 | 32 |
val group = Task_Queue.new_group (); |
28980
9d7ea903e877
refined Future.fork interfaces, no longer export Future.future;
wenzelm
parents:
28646
diff
changeset
|
33 |
val futures = map (fn x => Future.fork_group group (fn () => f x)) xs; |
28646 | 34 |
val _ = List.app (ignore o Future.join_result) futures; |
28549 | 35 |
in Future.join_results futures end |
36 |
else map (Exn.capture f) xs; |
|
28199 | 37 |
|
28443 | 38 |
fun map f xs = Exn.release_first (raw_map f xs); |
28199 | 39 |
|
40 |
fun get_some f xs = |
|
41 |
let |
|
42 |
exception FOUND of 'b option; |
|
43 |
fun found (Exn.Exn (FOUND some)) = some |
|
44 |
| found _ = NONE; |
|
45 |
val results = raw_map (fn x => (case f x of NONE => () | some => raise FOUND some)) xs; |
|
46 |
in |
|
47 |
(case get_first found results of |
|
48 |
SOME y => SOME y |
|
28443 | 49 |
| NONE => (Exn.release_first results; NONE)) |
28199 | 50 |
end; |
51 |
||
52 |
fun find_some P = get_some (fn x => if P x then SOME x else NONE); |
|
53 |
||
54 |
fun exists P = is_some o get_some (fn x => if P x then SOME () else NONE); |
|
55 |
fun forall P = not o exists (not o P); |
|
56 |
||
57 |
end; |