move backtracking into a stream
[scpubgit/DKit.git] / lib / DX / State.pm
index f273ddb..0ee431c 100644 (file)
@@ -36,9 +36,10 @@ sub mark_choice {
 
 sub backtrack {
   my ($self) = @_;
-  while (my ($state, $var) = @{$self->last_choice}) {
+  my ($state, $var) = ($self);
+  while (($state, $var) = @{$state->last_choice}) {
     $var->bound_value; $var->clear_bound_value;
-    return $state unless $var->bound_stream->is_exhausted;
+    return $state->mark_choice($var) unless $var->bound_stream->is_exhausted;
   }
   die "Out of options";
 }
@@ -48,4 +49,12 @@ sub then {
   $self->new(%$self, next_op => $then);
 }
 
+sub run {
+  my ($state) = @_;
+  while (my $op = $state->next_op) {
+    $state = $op->run($state);
+  }
+  return $state;
+}
+
 1;