fix: support if without else

If statements without an else should evaluate to nil if the condition is
not valid.  These are mainly used for side effects, but sometimes you
might want a value.
This commit is contained in:
Roman Godmaire 2024-05-04 17:43:38 -04:00
parent 8ac46f36a8
commit 30ebafb89d
2 changed files with 7 additions and 0 deletions

5
src/env/core.rs vendored
View file

@ -242,6 +242,11 @@ pub(super) fn core() -> HashMap<String, Node> {
( (
"if", "if",
Node::Special(|env, args| { Node::Special(|env, args| {
let mut args = args;
if args.len() == 2 {
args.push(Node::Nil)
}
arg_count!(3, args.len()); arg_count!(3, args.len());
let mut args = args.into_iter(); let mut args = args.into_iter();

View file

@ -141,6 +141,8 @@ mod test {
#[case("(if false true false)", "false")] #[case("(if false true false)", "false")]
#[case("(if 4 true false)", "true")] #[case("(if 4 true false)", "true")]
#[case("(if \"blue\" true false)", "true")] #[case("(if \"blue\" true false)", "true")]
#[case("(if true 3)", "3")]
#[case("(if false 3)", "()")]
// Functions // Functions
#[case("((fn* (a) a) 3)", "3")] #[case("((fn* (a) a) 3)", "3")]
#[case("((fn* (a) (+ a 2)) 1)", "3")] #[case("((fn* (a) (+ a 2)) 1)", "3")]