and and or added

This commit is contained in:
VaclavT 2021-03-28 13:37:54 +02:00
parent b0ff9dd934
commit 337fb2f80d
2 changed files with 23 additions and 7 deletions

23
ml.cpp
View File

@ -984,6 +984,27 @@ namespace builtin {
return MlValue(v);
}
// Evaluate logical and on a list of expressions (SPECIAL FORM)
MlValue do_and(std::vector<MlValue> args, MlEnvironment &env) {
if (args.size() < 2)
throw MlError(MlValue("and", do_and), env, TOO_FEW_ARGS);
for (size_t i = 0; i < args.size(); i++)
if (!args[i].eval(env).as_bool()) return MlValue::nil();
return MlValue{1l};
}
// Evaluate logical or on a list of expressions (SPECIAL FORM)
MlValue do_or(std::vector<MlValue> args, MlEnvironment &env) {
if (args.size() < 2)
throw MlError(MlValue("or", do_or), env, TOO_FEW_ARGS);
for (size_t i = 0; i < args.size(); i++)
if (args[i].eval(env).as_bool()) return MlValue{1l};
return MlValue::nil();
}
// Exit the program with an integer code
MlValue exit(std::vector<MlValue> args, MlEnvironment &env) {
@ -1760,6 +1781,8 @@ MlValue MlEnvironment::get(const std::string &name) const {
if (name == "defun") return MlValue("defun", builtin::defun);
if (name == "lambda") return MlValue("lambda", builtin::lambda);
if (name == "benchmark") return MlValue("benchmark", builtin::benchmark);
if (name == "and") return MlValue("and", builtin::do_and);
if (name == "or") return MlValue("or", builtin::do_or);
// Comparison operations
if (name == "=") return MlValue("=", builtin::eq);

View File

@ -1,13 +1,6 @@
; not a bool
(defun not (x) (if x 0 1))
; logical and
(defun and (a b) (if a (if b 1 0) 0))
; logical or
(defun or (a b) (if a 1 (if b 1 0)))
; negate a number
(defun neg (n) (- 0 n))