# 使用四十行Mathematica写一个LISP解释器

## 代码

Eval[cmd_] := (
If[Length[cmd] > 1,
car[cmd] @@ cdr[cmd]
, cmd]
);
car[lis_] := lis[[1]];
cdr[lis_] := (If[Length[lis] <= 1, {},
lis[[2 ;; Length[lis]]]]);
resetcar[lis_] := Clear[Evaluate[car[lis]]];
lambda[params_, expr_] :=
(
Module
[params, params = List[##];
Eval[expr]] &
);
setfunc[name_, expr_, params_] := (
DownValues[Evaluate[name]] = HoldPattern[
Evaluate[name @@ params]] ->
Eval[expr];
);
define[funclis_, expr_] :=
(
resetcar[funclis];
Module[
{params, body},
setfunc[car[funclis], expr, cdr[funclis]];
];
);
defwithrule[rule_] := (
DownValues[Evaluate[car[rule]]] = HoldPattern[
Evaluate[car[rule] @@ rule[[2]]]
] -> Eval[rule[[3]]];
);
defsyntax[rules_] := (
resetcar[rules];
defwithrule /@ cdr[rules];
);

eval[cmds_] := Eval /@ cmds;


eval[
{
{Set, haohao, 2},
{define, {plus, c_, d_}, {Plus, c, d}},
{plus, 3, 2},
{defsyntax,
{prefix,
{prefix,
{a_, plus, b_},
{plus, a, b}}
}
},
{Integrate, x^2, {x, 0, haohao}},
{prefix, 2, plus, 10},
{Plot, Sin[x/2], {x, 1, 100} },
{Sin, \[Pi]}
}
]