From 0b192278109da06880039f85d5d9a38700ffe840 Mon Sep 17 00:00:00 2001 From: MadMaurice Date: Sun, 4 Apr 2021 01:44:47 +0200 Subject: [PATCH] Add cond macro --- lib/Minilisp.pm | 37 +++++++++++++++++++++++++++++++++++++ t/cond.t | 5 +++++ 2 files changed, 42 insertions(+) create mode 100644 t/cond.t diff --git a/lib/Minilisp.pm b/lib/Minilisp.pm index 418901f..7da4a58 100644 --- a/lib/Minilisp.pm +++ b/lib/Minilisp.pm @@ -603,6 +603,43 @@ sub macro_defun { } $macros{defun} = \¯o_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} = \¯o_cond; + sub compile { my ($term) = @_; my @tokens = tokenize($term); diff --git a/t/cond.t b/t/cond.t new file mode 100644 index 0000000..b874226 --- /dev/null +++ b/t/cond.t @@ -0,0 +1,5 @@ +(expect "cond" 2 + (cond ((> 1 2) 10) + (f 20) + ((zerop 0) 2) + (t 10)))