summaryrefslogtreecommitdiff
path: root/src/components/lambda_reducer.tsx
blob: bef8fde500983391bf8f15f0c3016c474063d398 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { Rect, Node, Txt, Line, NodeProps } from "@motion-canvas/2d";
import { createRef, all, range, makeRef, DEFAULT } from "@motion-canvas/core";

import {
  CodeBlock,
  insert,
  edit,
  lines,
} from "@motion-canvas/2d/lib/components/CodeBlock";
import { Abstraction, Application, LambdaTerm, parse } from "../parser/parser";
import {
  EditOperation,
  calculateLevenshteinOperations,
} from "../utils/levenshtein";

export interface LambdaReducerProps extends NodeProps {
  lambdaTerm?: string;
  definitions?: Record<string, string>;
}

export class LambdaReducer extends Node {
  private readonly codeBlock = createRef<CodeBlock>();
  private reductions: string[];
  private ast: LambdaTerm;

  public constructor(props?: LambdaReducerProps) {
    super({
      ...props,
    });

    const functionDefinitions = props.definitions ?? {};
    let lambdaTerm = props.lambdaTerm ?? "((λ x . x) (λ y . y))";
    while (
      Object.keys(functionDefinitions).some((x) => lambdaTerm.includes(x))
    ) {
      lambdaTerm = Object.entries(functionDefinitions).reduce(
        (acc, [name, definition]) => {
          return acc.replace(new RegExp(name, "g"), definition);
        },
        lambdaTerm
      );
    }
    console.log(lambdaTerm);

    this.reductions = [props.lambdaTerm, lambdaTerm];
    this.ast = parse(lambdaTerm);
    this.add(
      <CodeBlock
        fontSize={25}
        ref={this.codeBlock}
        language="racket"
        code={this.getReductions()}
      ></CodeBlock>
    );
  }

  private getReductions() {
    return this.reductions.filter((x) => x).join("\n=> ");
  }

  private isApplication(ast: any): boolean {
    return ast.left && ast.right;
  }

  private isAbstraction(ast: any): boolean {
    return ast.param && ast.body;
  }

  private isVariable(ast: any): boolean {
    return !!ast.name;
  }

  private substitute(
    ast: LambdaTerm,
    param: string,
    replacement: LambdaTerm
  ): LambdaTerm {
    const node = ast as any;

    if (this.isVariable(node)) {
      return node.name === param ? replacement : node;
    } else if (this.isApplication(node)) {
      const left = this.substitute(node.left, param, replacement);
      const right = this.substitute(node.right, param, replacement);

      return { left, right } as Application;
    }

    return {
      param: node.param,
      body: this.substitute(node.body, param, replacement) as Abstraction,
    };
  }

  public getCode() {
    return this.emitCode(this.ast);
  }

  private betaReduceStep(ast: LambdaTerm): LambdaTerm {
    const node = ast as any;

    if (this.isApplication(node)) {
      const left = node.left as any;
      const right = node.right as any;

      if (this.isAbstraction(left)) {
        return this.substitute(left.body, left.param.name, right);
      }

      return {
        left: this.betaReduceStep(left),
        right: this.betaReduceStep(right),
      } as Application;
    }

    if (this.isAbstraction(node)) {
      return {
        param: node.param,
        body: this.betaReduceStep(node.body),
      } as Abstraction;
    }

    return node;
  }

  private emitCode(ast: LambdaTerm): string {
    const node = ast as any;

    if (this.isVariable(node)) {
      return node.name;
    } else if (this.isApplication(node)) {
      return `(${this.emitCode(node.left)} ${this.emitCode(node.right)})`;
    } else if (this.isAbstraction(node)) {
      return `(λ ${node.param.name}.${this.emitCode(node.body)})`;
    }

    throw new Error("Invalid lambda term");
  }

  public isDone() {
    return (
      this.emitCode(this.betaReduceStep(this.ast)) === this.emitCode(this.ast)
    );
  }

  public *step(duration: number) {
    yield* this.codeBlock().selection([], 0);

    const old = this.getReductions();
    const next = this.betaReduceStep(this.ast);
    const nextCode = this.emitCode(next);

    const operations = calculateLevenshteinOperations(
      this.reductions.at(-1),
      nextCode
    );

    yield* this.codeBlock().edit(duration)`${old}${insert(
      "\n=> " + this.reductions.at(-1)
    )}`;

    let code = `this.codeBlock().edit(duration)\`${old}\\n=> `;

    // this is SO FUCKING CURSED
    window.editInLambda = edit;
    window.insertInLambda = insert;
    for (const { operation, diff } of operations) {
      const next = `'${diff.new ?? ""}'`;
      const old = `'${diff.old ?? ""}'`;

      if (operation === EditOperation.Edit) {
        code += `\${editInLambda(${old}, ${next})}`;
        continue;
      }
      if (operation === EditOperation.Insert) {
        code += `\${insertInLambda(${next})}`;
        continue;
      }
      code += diff.new ?? "";
    }
    code += "`;";
    yield* eval(code);

    yield* this.codeBlock().selection(lines(this.reductions.length), 0.3);
    this.reductions.push(nextCode);
    this.ast = next;
  }
}