switch to passing prop to resolve in, fix bug in with_one_step, update output
[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
1350f664 11has propositions => (is => 'ro', isa => PropositionSequence, required => 1);
12
3e465d5d 13has alternatives => (is => 'ro', isa => AlternativeList, required => 1);
14
f25e6894 15sub next_proposition {
5787d20d 16 my ($self, $hyp) = @_;
17 $hyp ||= $self->current_hypothesis;
f25e6894 18 $self->propositions->members->[
5787d20d 19 $hyp->resolved_propositions->resolved_count
f25e6894 20 ];
21}
ccf0d4fe 22
3e465d5d 23sub new_for {
1350f664 24 my ($class, $hyp, $props) = @_;
3e465d5d 25 $class->new(
26 current_hypothesis => $hyp,
27 alternatives => [],
ccf0d4fe 28 next_step => DX::Step::InvokeNextPredicate->new(
f25e6894 29 proposition => $props->members->[0],
ccf0d4fe 30 ),
1350f664 31 propositions => $props,
3e465d5d 32 );
33}
9d759b64 34
35sub with_one_step {
36 my ($self) = @_;
37 my $hyp = $self->current_hypothesis;
e647e417 38 return undef unless my $step = $self->next_step;
39 my ($first_alt, @rest_alt) = my @alt = @{$self->alternatives};
40 my ($new_hyp, $alt_step) = $step->apply_to($hyp);
41 if ($new_hyp) {
42 return $self->but(
43 current_hypothesis => $new_hyp,
44 alternatives => [
45 ($alt_step
46 ? [ $hyp, $alt_step ]
47 : ()),
48 @alt
49 ],
ccf0d4fe 50 next_step => DX::Step::InvokeNextPredicate->new(
5787d20d 51 proposition => $self->next_proposition($new_hyp),
ccf0d4fe 52 ),
e647e417 53 );
9d759b64 54 }
e647e417 55 if ($alt_step) {
56 return $self->but(next_step => $alt_step);
57 }
58 return undef unless $first_alt;
59 trace 'search.backtrack.rewind_to' => $first_alt->[1];
60 return $self->but(
61 current_hypothesis => $first_alt->[0],
62 alternatives => \@rest_alt,
63 next_step => $first_alt->[1],
64 );
9d759b64 65}
66
67sub find_solution {
68 my $state = $_[0];
f25e6894 69 while ($state and $state->next_proposition) {
9d759b64 70 $state = $state->with_one_step;
71 }
72e5c0e0 72 trace 'search.solution.hyp' => $state->current_hypothesis if $state;
9d759b64 73 return $state;
74}
75
76sub force_backtrack {
77 my ($self) = @_;
f458fa2c 78 my ($first_alt, @rest_alt) = @{$self->alternatives};
79 return undef unless $first_alt;
72e5c0e0 80 trace 'search.backtrack.forced' => $first_alt->[0];
9d759b64 81 return ref($self)->new(
82 current_hypothesis => $first_alt->[0],
e647e417 83 next_step => $first_alt->[1],
1350f664 84 alternatives => \@rest_alt,
85 propositions => $self->propositions,
9d759b64 86 );
87}
88
89sub find_next_solution {
90 my ($self) = @_;
91 return undef unless my $bt = $self->force_backtrack;
92 return $bt->find_solution;
93}
94
951;