598 lemma the_eq [code]: "the A = singleton (\<lambda>x. not_unique A) A" |
598 lemma the_eq [code]: "the A = singleton (\<lambda>x. not_unique A) A" |
599 by (rule the_eqI) (simp add: singleton_def not_unique_def) |
599 by (rule the_eqI) (simp add: singleton_def not_unique_def) |
600 |
600 |
601 code_reflect Predicate |
601 code_reflect Predicate |
602 datatypes pred = Seq and seq = Empty | Insert | Join |
602 datatypes pred = Seq and seq = Empty | Insert | Join |
603 functions map |
|
604 |
603 |
605 ML {* |
604 ML {* |
606 signature PREDICATE = |
605 signature PREDICATE = |
607 sig |
606 sig |
|
607 val anamorph: ('a -> ('b * 'a) option) -> int -> 'a -> 'b list * 'a |
608 datatype 'a pred = Seq of (unit -> 'a seq) |
608 datatype 'a pred = Seq of (unit -> 'a seq) |
609 and 'a seq = Empty | Insert of 'a * 'a pred | Join of 'a pred * 'a seq |
609 and 'a seq = Empty | Insert of 'a * 'a pred | Join of 'a pred * 'a seq |
|
610 val map: ('a -> 'b) -> 'a pred -> 'b pred |
610 val yield: 'a pred -> ('a * 'a pred) option |
611 val yield: 'a pred -> ('a * 'a pred) option |
611 val yieldn: int -> 'a pred -> 'a list * 'a pred |
612 val yieldn: int -> 'a pred -> 'a list * 'a pred |
612 val map: ('a -> 'b) -> 'a pred -> 'b pred |
|
613 end; |
613 end; |
614 |
614 |
615 structure Predicate : PREDICATE = |
615 structure Predicate : PREDICATE = |
616 struct |
616 struct |
617 |
617 |
|
618 fun anamorph f k x = |
|
619 (if k = 0 then ([], x) |
|
620 else case f x |
|
621 of NONE => ([], x) |
|
622 | SOME (v, y) => let |
|
623 val k' = k - 1; |
|
624 val (vs, z) = anamorph f k' y |
|
625 in (v :: vs, z) end); |
|
626 |
618 datatype pred = datatype Predicate.pred |
627 datatype pred = datatype Predicate.pred |
619 datatype seq = datatype Predicate.seq |
628 datatype seq = datatype Predicate.seq |
620 |
629 |
621 fun map f = Predicate.map f; |
630 fun map f = @{code Predicate.map} f; |
622 |
631 |
623 fun yield (Seq f) = next (f ()) |
632 fun yield (Seq f) = next (f ()) |
624 and next Empty = NONE |
633 and next Empty = NONE |
625 | next (Insert (x, P)) = SOME (x, P) |
634 | next (Insert (x, P)) = SOME (x, P) |
626 | next (Join (P, xq)) = (case yield P |
635 | next (Join (P, xq)) = (case yield P |
627 of NONE => next xq |
636 of NONE => next xq |
628 | SOME (x, Q) => SOME (x, Seq (fn _ => Join (Q, xq)))); |
637 | SOME (x, Q) => SOME (x, Seq (fn _ => Join (Q, xq)))); |
629 |
638 |
630 fun anamorph f k x = (if k = 0 then ([], x) |
639 fun yieldn k = anamorph yield k; |
631 else case f x |
|
632 of NONE => ([], x) |
|
633 | SOME (v, y) => let |
|
634 val (vs, z) = anamorph f (k - 1) y |
|
635 in (v :: vs, z) end); |
|
636 |
|
637 fun yieldn P = anamorph yield P; |
|
638 |
640 |
639 end; |
641 end; |
640 *} |
642 *} |
641 |
643 |
642 text {* Conversion from and to sets *} |
644 text {* Conversion from and to sets *} |