Add cond macro

This commit is contained in:
madmaurice 2021-04-04 01:44:47 +02:00
parent ed59a6a04e
commit 0b19227810
2 changed files with 42 additions and 0 deletions

View file

@ -603,6 +603,43 @@ sub macro_defun {
}
$macros{defun} = \&macro_defun;
sub macro_cond {
my $ts = shift;
my @cases;
while ($ts->[0]->{type} != RPAREN)
{
die "Expected ( before case in cond"
unless (shift @$ts)->{type} == LPAREN;
my $condition = parser_expr($ts);
my $work = parser_expr($ts);
die "Expected ) after case in cond"
unless (shift @$ts)->{type} == RPAREN;
push @cases, {
condition => $condition,
work => $work,
};
}
return sub {
my $ctx = shift;
foreach my $case (@cases)
{
if($case->{condition}->($ctx))
{
return $case->{work}->($ctx);
}
}
return undef;
}
}
$macros{cond} = \&macro_cond;
sub compile {
my ($term) = @_;
my @tokens = tokenize($term);

5
t/cond.t Normal file
View file

@ -0,0 +1,5 @@
(expect "cond" 2
(cond ((> 1 2) 10)
(f 20)
((zerop 0) 2)
(t 10)))