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)))