restructure searching so with_one_step is actually one step
[scpubgit/DX.git] / lib / DX / SearchState.pm
CommitLineData
9d759b64 1package DX::SearchState;
2
a1aab147 3use Types::Standard qw(Maybe);
e647e417 4use DX::Step::InvokeNextPredicate;
9d759b64 5use DX::Class;
6
3e465d5d 7has current_hypothesis => (is => 'ro', isa => Hypothesis, required => 1);
9d759b64 8
e647e417 9has next_step => (is => 'ro', isa => Maybe[Step]);
9d759b64 10
3e465d5d 11has alternatives => (is => 'ro', isa => AlternativeList, required => 1);
12
13sub new_for {
14 my ($class, $hyp) = @_;
15 $class->new(
16 current_hypothesis => $hyp,
17 alternatives => [],
e647e417 18 next_step => DX::Step::InvokeNextPredicate->new,
3e465d5d 19 );
20}
9d759b64 21
22sub with_one_step {
23 my ($self) = @_;
24 my $hyp = $self->current_hypothesis;
e647e417 25 return undef unless my $step = $self->next_step;
26 my ($first_alt, @rest_alt) = my @alt = @{$self->alternatives};
27 my ($new_hyp, $alt_step) = $step->apply_to($hyp);
28 if ($new_hyp) {
29 return $self->but(
30 current_hypothesis => $new_hyp,
31 alternatives => [
32 ($alt_step
33 ? [ $hyp, $alt_step ]
34 : ()),
35 @alt
36 ],
37 next_step => DX::Step::InvokeNextPredicate->new,
38 );
9d759b64 39 }
e647e417 40 if ($alt_step) {
41 return $self->but(next_step => $alt_step);
42 }
43 return undef unless $first_alt;
44 trace 'search.backtrack.rewind_to' => $first_alt->[1];
45 return $self->but(
46 current_hypothesis => $first_alt->[0],
47 alternatives => \@rest_alt,
48 next_step => $first_alt->[1],
49 );
9d759b64 50}
51
52sub find_solution {
53 my $state = $_[0];
54 while ($state and @{$state->current_hypothesis->outstanding_propositions}) {
55 $state = $state->with_one_step;
56 }
72e5c0e0 57 trace 'search.solution.hyp' => $state->current_hypothesis if $state;
9d759b64 58 return $state;
59}
60
61sub force_backtrack {
62 my ($self) = @_;
f458fa2c 63 my ($first_alt, @rest_alt) = @{$self->alternatives};
64 return undef unless $first_alt;
72e5c0e0 65 trace 'search.backtrack.forced' => $first_alt->[0];
9d759b64 66 return ref($self)->new(
67 current_hypothesis => $first_alt->[0],
e647e417 68 next_step => $first_alt->[1],
9d759b64 69 alternatives => \@rest_alt
70 );
71}
72
73sub find_next_solution {
74 my ($self) = @_;
75 return undef unless my $bt = $self->force_backtrack;
76 return $bt->find_solution;
77}
78
791;