KumiScript/interpreter/LispProcedure.cs

49 lines
No EOL
1.4 KiB
C#

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(Expression 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), ")");
}
public List<Symbol> GetParameters()
{
return _parameters;
}
}
}