KumiScript/interpreter/LispProcedure.cs
2024-01-25 23:37:51 -06:00

46 lines
No EOL
1.4 KiB
C#

using System.DirectoryServices;
namespace KumiScript.Interpreter
{
public class LispProcedure : Procedure
{
readonly List<Symbol> _parameters;
readonly Expression _body;
readonly Environment _closureEnv;
public LispProcedure(List<Symbol> parameters, Expression body, Environment closureEnv)
{
_parameters = parameters;
_body = body;
_closureEnv = closureEnv;
}
public override Expression ApplyWithArgs(ListExpression args, Environment env)
{
List<Expression> evaluatedArgs = args.EvalMembers(env);
if (_parameters.Count != evaluatedArgs.Count)
throw new InterpreterInvalidApplicationException();
Environment inner = MapArgs(evaluatedArgs, _closureEnv);
return _body.Eval(inner);
}
private Environment MapArgs(List<Expression> args, Environment env)
{
Environment inner = new Environment(env);
for (int i = 0; i < _parameters.Count; i++)
inner.AddSymbol(_parameters[i], args[i]);
return inner;
}
public override bool IsPrimitive()
{
return false;
}
public override string ToString()
{
return string.Concat("λ(", string.Join(' ', _parameters), ")");
}
}
}