switch SearchState to using Backtrack step
[scpubgit/DX.git] / lib / DX / SearchState.pm
CommitLineData
9d759b64 1package DX::SearchState;
2
a1aab147 3use Types::Standard qw(Maybe);
985b43d1 4use DX::Step::Backtrack;
e647e417 5use DX::Step::InvokeNextPredicate;
9d759b64 6use DX::Class;
7
3e465d5d 8has current_hypothesis => (is => 'ro', isa => Hypothesis, required => 1);
9d759b64 9
e647e417 10has next_step => (is => 'ro', isa => Maybe[Step]);
9d759b64 11
1350f664 12has propositions => (is => 'ro', isa => PropositionSequence, required => 1);
13
3e465d5d 14has alternatives => (is => 'ro', isa => AlternativeList, required => 1);
15
f25e6894 16sub next_proposition {
5787d20d 17 my ($self, $hyp) = @_;
18 $hyp ||= $self->current_hypothesis;
f25e6894 19 $self->propositions->members->[
5787d20d 20 $hyp->resolved_propositions->resolved_count
f25e6894 21 ];
22}
ccf0d4fe 23
3e465d5d 24sub new_for {
1350f664 25 my ($class, $hyp, $props) = @_;
3e465d5d 26 $class->new(
27 current_hypothesis => $hyp,
28 alternatives => [],
ccf0d4fe 29 next_step => DX::Step::InvokeNextPredicate->new(
f25e6894 30 proposition => $props->members->[0],
ccf0d4fe 31 ),
1350f664 32 propositions => $props,
3e465d5d 33 );
34}
9d759b64 35
36sub with_one_step {
37 my ($self) = @_;
38 my $hyp = $self->current_hypothesis;
e647e417 39 return undef unless my $step = $self->next_step;
5d243619 40 my ($new_ss) = $step->apply_to($self);
41 return $new_ss if $new_ss;
7506f4ca 42 my ($first_alt, @rest_alt) = @{$self->alternatives};
e647e417 43 return undef unless $first_alt;
44 trace 'search.backtrack.rewind_to' => $first_alt->[1];
45 return $self->but(
985b43d1 46 next_step => DX::Step::Backtrack->new,
e647e417 47 );
9d759b64 48}
49
9d759b64 50sub force_backtrack {
51 my ($self) = @_;
f458fa2c 52 my ($first_alt, @rest_alt) = @{$self->alternatives};
53 return undef unless $first_alt;
72e5c0e0 54 trace 'search.backtrack.forced' => $first_alt->[0];
9d759b64 55 return ref($self)->new(
56 current_hypothesis => $first_alt->[0],
e647e417 57 next_step => $first_alt->[1],
1350f664 58 alternatives => \@rest_alt,
59 propositions => $self->propositions,
9d759b64 60 );
61}
62
9d759b64 631;