Skip to content

Commit

Permalink
REPL: added support for refering to previous output values.
Browse files Browse the repository at this point in the history
Using the syntax `#n`:

    >> 3+4
    #1 = 7
    >> sqrt(#1)
    #2 = 2.64575131106459059050161575363926042571025918308
    >>

The history can be reseted with the `reset` keyword.
  • Loading branch information
trizen committed May 9, 2022
1 parent 83fe713 commit 50343bb
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
23 changes: 22 additions & 1 deletion bin/sidef
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,8 @@ EOT

my $tΔ = 0;

my @values;

MAINLOOP: {
my $line = '';

Expand Down Expand Up @@ -535,6 +537,8 @@ EOT
$vars = $copy_hash->($sidef->{parser}{vars});
$ref_vars_refs = $copy_hash->($sidef->{parser}{ref_vars_refs});

$line =~ s{#([1-9][0-9]*)\b}{($1 <= scalar(@values)) ? $values[$1-1]->{value} : "#$1"}ge;

my $ccode = eval { $sidef->compile_code($line, $args{r} ? 'Sidef' : ($args{R} || 'Perl')) };

if ($@) {
Expand All @@ -550,6 +554,7 @@ EOT
$sidef->execute_code(''); # warm-up
undef $vars;
undef $ref_vars_refs;
@values = ();
redo;
}

Expand Down Expand Up @@ -622,7 +627,13 @@ EOT
);
$dump = "($dump)" if @results > 1;

say "=> $dump";
push @values,
{
type => ((scalar(@results) == 1) ? 'scalar' : 'list'),
value => $dump,
};

say "#" . scalar(@values) . " = $dump";
}
redo;
}
Expand Down Expand Up @@ -877,6 +888,12 @@ The REPL supports the following special commands:
>> ##
=item * Refer to a previous output value, using the C<#n> syntax:
>> 3+4
#1 = 7
>> sqrt(#1)
=item * Save the code from the REPL inside a file:
>> # save filename.sf
Expand All @@ -885,6 +902,10 @@ The REPL supports the following special commands:
>> # load filename.sf
=item * Reset the REPL:
>> reset
=item * Close the REPL:
>> quit
Expand Down
2 changes: 1 addition & 1 deletion lib/Sidef/Types/Number/Number.pm
Original file line number Diff line number Diff line change
Expand Up @@ -1334,7 +1334,7 @@ package Sidef::Types::Number::Number {
substr($im, 0, 1, '');
}

$im = '' if $im eq '1';
#$im = '' if $im eq '1';
return ($re eq '0' ? $sign eq '+' ? "${im}i" : "$sign${im}i" : "$re$sign${im}i");
}
}
Expand Down

0 comments on commit 50343bb

Please sign in to comment.