From e163fdce599724a1b40da8a19f56c9668a33b2c2 Mon Sep 17 00:00:00 2001 From: MadMaurice Date: Sun, 4 Apr 2021 01:53:18 +0200 Subject: [PATCH] Add when, unless --- lib/Minilisp.pm | 38 ++++++++++++++++++++++++++++++++++++++ t/unless.t | 5 +++++ t/when.t | 5 +++++ 3 files changed, 48 insertions(+) create mode 100644 t/unless.t create mode 100644 t/when.t diff --git a/lib/Minilisp.pm b/lib/Minilisp.pm index 7da4a58..88cc55c 100644 --- a/lib/Minilisp.pm +++ b/lib/Minilisp.pm @@ -640,6 +640,44 @@ sub macro_cond { } $macros{cond} = \¯o_cond; +sub macro_when { + my $ts = shift; + + my $condition = parser_expr($ts); + my $work = parser_expr($ts); + + return sub { + my $ctx = shift; + + if ($condition->($ctx)) + { + return $work->($ctx); + } + + return undef; + } +} +$macros{when} = \¯o_when; + +sub macro_unless { + my $ts = shift; + + my $condition = parser_expr($ts); + my $work = parser_expr($ts); + + return sub { + my $ctx = shift; + + if (!$condition->($ctx)) + { + return $work->($ctx); + } + + return undef; + } +} +$macros{unless} = \¯o_unless; + sub compile { my ($term) = @_; my @tokens = tokenize($term); diff --git a/t/unless.t b/t/unless.t new file mode 100644 index 0000000..774b7b7 --- /dev/null +++ b/t/unless.t @@ -0,0 +1,5 @@ +(expect "unless - true condition" + (null (unless t 'fail))) + +(expect "unless - false condition" + (equal 'ok (unless f 'ok))) diff --git a/t/when.t b/t/when.t new file mode 100644 index 0000000..076fcac --- /dev/null +++ b/t/when.t @@ -0,0 +1,5 @@ +(expect "when - true condition" + (equal 'ok (when t 'ok))) + +(expect "when - false condition" + (null (when f 'fail)))