Execute Brain****/Raku: Difference between revisions

From Rosetta Code
Content added Content deleted
(constructor can't initialize a private variable for some reason)
m (No need to bless self. Make into a single runnable file.)
Line 1: Line 1:
{{works with|Rakudo|2018.03}}
<lang perl6>class BFInterpreter {
<lang perl6>class BFInterpreter {
has @.code;
has @.code;
Line 8: Line 9:


method new (Str $code) {
method new (Str $code) {
BFInterpreter.bless(*,code => $code.lines.comb);
BFInterpreter.bless(code => $code.lines.comb);
}
}


Line 46: Line 47:
}
}
}
}
}
}</lang>


Test: "Hello World" program:
# Test: "Hello World" program:

<lang perl6>my $code = "++++++++++
my $code = "++++++++++
[>+++++++>++++++++++>+++>+<<<<-]
[>+++++++>++++++++++>+++>+<<<<-]
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.
>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.

Revision as of 19:06, 1 April 2018

Works with: Rakudo version 2018.03

<lang perl6>class BFInterpreter {

   has @.code;
   has @!mem;
   has @!loop_stack;
   has @!input_buffer;
   has $!m;
   has $!c;
   method new (Str $code) {
       BFInterpreter.bless(code => $code.lines.comb);
   }
   method run {
       $!c = 0;
       $!m = 0;
       while $!c < @.code {
           given @.code[$!c] {
               when '>' { $!m++ }
               when '<' { $!m-- }
               when '+' { @!mem[$!m]++ }
               when '-' { @!mem[$!m]-- }
               when '.' { @!mem[$!m].chr.print }
               when ',' {
                   @!input_buffer = $*IN.get.comb unless @!input_buffer.elems > 0;
                   @!mem[$!m] = @!input_buffer.shift;
               }
               when '[' {
                   @!mem[$!m] == 0 ?? self!jump !! @!loop_stack.push($!c);
               }
               when ']' {
                   my $b = @!loop_stack.pop - 1;
                   $!c = $b if @!mem[$!m] > 0;
               }
           }

$!c++;

       }
   }
   method !jump {
       my $depth = 1;
       while $depth {
           $!c++;
           die "unbalanced code" if $!c >= @.code.elems;
           $depth++ if @.code[$!c] eq '[';
           $depth-- if @.code[$!c] eq ']';
       }
   }

}

  1. Test: "Hello World" program:

my $code = "++++++++++

          [>+++++++>++++++++++>+++>+<<<<-]
          >++.>+.+++++++..+++.>++.<<+++++++++++++++.>.
          +++.------.--------.>+.>.";

my $bfi = BFInterpreter.new($code); $bfi.run; </lang>