mark propositionless search states as solutions
[scpubgit/DX.git] / lib / DX / SearchState.pm
1 package DX::SearchState;
2
3 use Types::Standard qw(Maybe);
4 use DX::Step::Backtrack;
5 use DX::Step::InvokeNextPredicate;
6 use DX::Class;
7
8 has current_hypothesis => (is => 'ro', isa => Hypothesis, required => 1);
9
10 has next_step => (is => 'ro', isa => Maybe[Step]);
11
12 has propositions => (is => 'ro', isa => PropositionSequence, required => 1);
13
14 has alternatives => (is => 'ro', isa => AlternativeList, required => 1);
15
16 has is_solution_state => (is => 'ro', required => 1);
17
18 sub next_proposition {
19   my ($self, $hyp) = @_;
20   $hyp ||= $self->current_hypothesis;
21   $self->propositions->members->[
22     $hyp->resolved_propositions->resolved_count
23   ];
24 }
25
26 sub new_for {
27   my ($class, $hyp, $props) = @_;
28   $class->new(
29     current_hypothesis => $hyp,
30     alternatives => [],
31     propositions => $props,
32     (@{$props->members}
33       ? (
34           next_step => DX::Step::InvokeNextPredicate->new(
35             proposition => $props->members->[0],
36           ),
37           is_solution_state => 0,
38         )
39       : ( is_solution_state => 1 )
40     ),
41   );
42 }
43
44 sub with_one_step {
45   my ($self) = @_;
46   return undef unless my $step = $self->next_step;
47   return $step->apply_to($self);
48 }
49
50 sub force_backtrack {
51   my ($self) = @_;
52   my ($first_alt, @rest_alt) = @{$self->alternatives};
53   return undef unless $first_alt;
54   trace 'search.backtrack.forced' => $first_alt->[0];
55   return $self->but(
56     next_step => DX::Step::Backtrack->new,
57   )->with_one_step;
58 }
59
60 1;