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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
|
document.addEventListener('DOMContentLoaded', () => {
const GRID_SIZE = 50;
const CELL_SIZE = 10; // Adjust for desired visual size
const CANVAS_WIDTH = GRID_SIZE * CELL_SIZE;
const CANVAS_HEIGHT = GRID_SIZE * CELL_SIZE;
const canvas = document.getElementById('gridCanvas');
const ctx = canvas.getContext('2d');
const input = document.getElementById('kInput');
const runButton = document.getElementById('runButton');
const output = document.getElementById('output');
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
// --- Grid State ---
let G = Array(GRID_SIZE).fill().map(() => Array(GRID_SIZE).fill(0)); // 2D matrix grid state
// --- Drawing ---
function drawGridLines() {
ctx.strokeStyle = '#eee'; // Light gray grid lines
ctx.lineWidth = 1;
for (let i = 0; i <= GRID_SIZE; i++) {
// Vertical lines
ctx.beginPath();
ctx.moveTo(i * CELL_SIZE + 0.5, 0);
ctx.lineTo(i * CELL_SIZE + 0.5, CANVAS_HEIGHT);
ctx.stroke();
// Horizontal lines
ctx.beginPath();
ctx.moveTo(0, i * CELL_SIZE + 0.5);
ctx.lineTo(CANVAS_WIDTH, i * CELL_SIZE + 0.5);
ctx.stroke();
}
}
function drawCells() {
ctx.fillStyle = '#333'; // Color for 'on' cells
for (let row = 0; row < GRID_SIZE; row++) {
for (let col = 0; col < GRID_SIZE; col++) {
if (G[row][col] === 1) {
ctx.fillRect(col * CELL_SIZE, row * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
}
function redraw() {
// Clear canvas
ctx.fillStyle = '#fff'; // Background color
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
drawGridLines();
drawCells();
}
// --- K-like Interpreter ---
// Simple tokenizer (basic version)
function tokenize(code) {
// First, normalize whitespace
code = code.replace(/\s+/g, ' ').trim();
// Define all operators and special characters
const operators = ['+', '-', '*', '/', '%', '(', ')', '!', '@', ':', '=', '<', '>', "'"];
// Add spaces around all operators
operators.forEach(op => {
// Use a regex that ensures we don't double-space
const regex = new RegExp(`\\${op}`, 'g');
code = code.replace(regex, ` ${op} `);
});
// Normalize spaces again
code = code.replace(/\s+/g, ' ').trim();
// Split into tokens
const tokens = code.split(' ');
// Filter out empty tokens and log for debugging
const filteredTokens = tokens.filter(t => t.length > 0);
console.log('Tokenized:', filteredTokens);
return filteredTokens;
}
// Evaluator for expressions (recursive descent style)
// Handles numbers, !, +, -, *, %, (), G, where, and K-style adverbs
function evaluateExpression(tokens) {
if (!tokens || tokens.length === 0) throw new Error("Empty expression");
function parseAtom() {
let token = tokens.shift();
if (!token) throw new Error("Unexpected end of expression");
console.log('Parsing atom:', token, 'Remaining tokens:', tokens); // Debug log
if (token === '!') { // Iota (prefix)
const operand = parseAtom();
if (typeof operand !== 'number' || !Number.isInteger(operand) || operand < 0) {
throw new Error("Operand for ! (iota) must be a non-negative integer");
}
// Create a 2D array of indices
const result = [];
for (let row = 0; row < GRID_SIZE; row++) {
for (let col = 0; col < GRID_SIZE; col++) {
result.push([row, col]);
}
}
return result;
} else if (token === "'") { // Each adverb
const operand = parseAtom();
if (!Array.isArray(operand)) {
throw new Error("Each adverb (') requires an array operand");
}
// Apply the operation to each element
return operand.map(x => {
if (Array.isArray(x)) {
return x.map(y => y);
}
return x;
});
} else if (token === '/') { // Over adverb
const operand = parseAtom();
if (!Array.isArray(operand)) {
throw new Error("Over adverb (/) requires an array operand");
}
// Reduce the array
return operand.reduce((a, b) => {
if (Array.isArray(a) && Array.isArray(b)) {
return a.map((x, i) => x + b[i]);
}
return a + b;
});
} else if (token === '(') {
console.log('Found opening parenthesis, remaining tokens:', tokens); // Debug log
const value = parseAddSub(); // Start parsing inside parenthesis
console.log('After parsing inside parentheses, next token:', tokens[0]); // Debug log
if (tokens.length === 0) {
throw new Error("Missing closing parenthesis");
}
const nextToken = tokens.shift();
if (nextToken !== ')') {
throw new Error(`Expected closing parenthesis, got: ${nextToken}`);
}
return value;
} else if (token === 'G') {
// Return the 2D matrix as a flat array of [row,col] pairs
const result = [];
for (let row = 0; row < GRID_SIZE; row++) {
for (let col = 0; col < GRID_SIZE; col++) {
result.push([row, col]);
}
}
return result;
} else if (token === 'where') { // Special 'where G=1' form
if (tokens.shift() !== 'G') throw new Error("Expected 'G' after 'where'");
if (tokens.shift() !== '=') throw new Error("Expected '=' after 'where G'");
if (tokens.shift() !== '1') throw new Error("Expected '1' after 'where G='");
const indices = [];
for(let row = 0; row < GRID_SIZE; row++) {
for(let col = 0; col < GRID_SIZE; col++) {
if (G[row][col] === 1) {
indices.push([row, col]);
}
}
}
return indices;
} else if (/^-?\d+$/.test(token)) { // Integer
return parseInt(token, 10);
} else {
throw new Error(`Unrecognized token: ${token}`);
}
}
function parseMulDivMod() {
let left = parseAtom();
while (tokens.length > 0 && (tokens[0] === '*' || tokens[0] === '%' || tokens[0] === '/')) {
const op = tokens.shift();
const right = parseAtom();
left = applyOperation(left, right, op);
}
return left;
}
function parseAddSub() {
let left = parseMulDivMod();
while (tokens.length > 0 && (tokens[0] === '+' || tokens[0] === '-')) {
const op = tokens.shift();
const right = parseMulDivMod();
left = applyOperation(left, right, op);
}
return left;
}
function parseComparison() {
let left = parseAddSub();
while (tokens.length > 0 && (tokens[0] === '<' || tokens[0] === '>' || tokens[0] === '=')) {
const op = tokens.shift();
const right = parseAddSub();
left = applyOperation(left, right, op);
}
return left;
}
const result = parseComparison();
if (tokens.length > 0) {
throw new Error(`Unexpected tokens remaining: ${tokens.join(' ')}`);
}
return result;
}
// Helper for arithmetic operations (handles scalar/list combinations)
function applyOperation(a, b, op) {
const isAList = Array.isArray(a);
const isBList = Array.isArray(b);
if (!isAList && !isBList) { // Scalar op Scalar
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '%': return b === 0 ? NaN : a % b; // Modulo
case '/': return b === 0 ? NaN : a / b; // Division
case '<': return a < b ? 1 : 0; // Convert boolean to 0/1
case '>': return a > b ? 1 : 0;
case '=': return a === b ? 1 : 0;
default: throw new Error(`Unknown operator: ${op}`);
}
} else if (isAList && !isBList) { // List op Scalar
return a.map(val => {
if (Array.isArray(val)) {
return val.map(x => applyOperation(x, b, op));
}
return applyOperation(val, b, op);
});
} else if (!isAList && isBList) { // Scalar op List
return b.map(val => {
if (Array.isArray(val)) {
return val.map(x => applyOperation(a, x, op));
}
return applyOperation(a, val, op);
});
} else { // List op List
if (a.length !== b.length) throw new Error(`List length mismatch for operator ${op}: ${a.length} vs ${b.length}`);
return a.map((val, i) => {
if (Array.isArray(val) && Array.isArray(b[i])) {
return val.map((x, j) => applyOperation(x, b[i][j], op));
}
return applyOperation(val, b[i], op);
});
}
}
// Main execution function
function executeK(code) {
code = code.trim();
if (!code) return; // Ignore empty input
try {
// Specific Cases: G : 0 or G : 1
if (code === 'G : 0') {
G = Array(GRID_SIZE).fill().map(() => Array(GRID_SIZE).fill(0));
setOutput("Grid cleared.", "success");
return;
}
if (code === 'G : 1') {
G = Array(GRID_SIZE).fill().map(() => Array(GRID_SIZE).fill(1));
setOutput("Grid filled.", "success");
return;
}
// General Case: G @ indices : values
const assignMatch = code.match(/^G\s*@\s*(.+?)\s*:\s*(.+)$/);
if (assignMatch) {
const indexExpr = assignMatch[1].trim();
const valueExpr = assignMatch[2].trim();
const indices = evaluateExpression(tokenize(indexExpr));
const values = evaluateExpression(tokenize(valueExpr));
const indicesArray = Array.isArray(indices) ? indices : [indices];
const valuesArray = Array.isArray(values) ? values : [values];
if (indicesArray.length === 0) {
setOutput("Warning: Assignment applied to empty index list.", "info");
return;
}
let assignments = 0;
for (let i = 0; i < indicesArray.length; i++) {
const idx = indicesArray[i];
// Handle both 1D and 2D indices
let row, col;
if (Array.isArray(idx)) {
[row, col] = idx;
} else {
row = Math.floor(idx / GRID_SIZE);
col = idx % GRID_SIZE;
}
// Basic validation
if (typeof row !== 'number' || !Number.isInteger(row) ||
typeof col !== 'number' || !Number.isInteger(col)) {
console.warn(`Skipping invalid index: ${idx}`);
continue;
}
if (row >= 0 && row < GRID_SIZE && col >= 0 && col < GRID_SIZE) {
// Cycle through values if needed
const valueToAssign = valuesArray[i % valuesArray.length];
if (valueToAssign === 0 || valueToAssign === 1) {
G[row][col] = valueToAssign;
assignments++;
} else {
console.warn(`Skipping invalid value assignment (${valueToAssign}) at index [${row},${col}]. Must be 0 or 1.`);
}
} else {
console.warn(`Skipping out-of-bounds index: [${row},${col}]`);
}
}
setOutput(`OK. Performed ${assignments} assignments.`, "success");
} else {
// Try evaluating as a general expression (e.g., for debugging)
// This won't modify G unless the expression itself involves an assignment (not implemented here)
const result = evaluateExpression(tokenize(code));
setOutput(`Evaluated: ${JSON.stringify(result)}`, "info");
// throw new Error("Invalid syntax. Expected 'G : 0', 'G : 1', or 'G @ indices : values'");
}
} catch (error) {
setOutput(`Error: ${error.message}`, "error");
console.error("K execution error:", error);
}
}
// --- Output Helper ---
function setOutput(message, type = "info") { // type: info, success, error
output.textContent = message;
output.className = type; // Use CSS classes for styling
}
// --- Event Listeners ---
function handleRun() {
const code = input.value;
executeK(code);
redraw();
// Optional: Clear input after running
// input.value = '';
}
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
handleRun();
}
});
runButton.addEventListener('click', handleRun);
// --- Initial Draw ---
setOutput("Grid initialized. Enter commands below.", "info");
redraw();
});
|