This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2023-06-14
Channels
- # babashka (43)
- # beginners (47)
- # biff (1)
- # calva (16)
- # cider (7)
- # clerk (6)
- # clj-kondo (39)
- # cljdoc (49)
- # clojure (29)
- # clojure-brasil (1)
- # clojure-europe (93)
- # clojure-losangeles (1)
- # clojure-norway (34)
- # conjure (7)
- # datalevin (8)
- # events (1)
- # gratitude (3)
- # honeysql (6)
- # hyperfiddle (2)
- # introduce-yourself (1)
- # javascript (1)
- # jobs-discuss (9)
- # lsp (3)
- # malli (10)
- # off-topic (8)
- # pedestal (3)
- # rewrite-clj (2)
- # shadow-cljs (17)
- # sql (33)
- # vim (1)
- # xtdb (31)
Hey all, hope everything is well. I’m writing a mini clojure interpreter in js and has a small issue as I’m not able to evaluate let
.
const readline = require('readline');
// Store variables and their values
const environment = {};
function evaluateExpression(expression) {
// Remove parentheses and split the expression into tokens
const tokens = expression.replace(/[()]/g, '').split(' ');
// Check if it's a variable assignment using 'let'
if (tokens[0] === 'let') {
// Extract variable names and values
const assignments = tokens[1].substring(1, tokens[1].length - 1).split(' ');
for (let i = 0; i < assignments.length; i += 2) {
const variable = assignments[i];
const value = parseFloat(assignments[i + 1]);
environment[variable] = value;
}
// Evaluate the body expression
const bodyExpression = tokens.slice(2).join(' ');
return evaluateExpression(bodyExpression);
}
// Check if the token is a variable
if (tokens[0] in environment) {
tokens[0] = environment[tokens[0]];
}
// Extract the operator and operands
const operator = tokens[0];
const operands = tokens.slice(1).map((token) => {
if (token in environment) {
return environment[token];
}
return parseFloat(token);
});
// Perform the arithmetic operation based on the operator
let result;
switch (operator) {
case '+':
result = operands.reduce((a, b) => a + b, 0);
break;
case '-':
result = operands.reduce((a, b) => a - b);
break;
case '*':
result = operands.reduce((a, b) => a * b, 1);
break;
case '/':
result = operands.reduce((a, b) => a / b);
break;
default:
result = 'Invalid operator';
}
return result;
}
function startREPL() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: '>> ',
});
rl.prompt();
rl.on('line', (input) => {
if (input === 'exit') {
rl.close();
} else {
const result = evaluateExpression(input);
console.log(result);
rl.prompt();
}
}).on('close', () => {
console.log('Exiting REPL');
process.exit(0);
});
}
startREPL();
I can get normal math working, (+ 5 2) 7
. But when tried (let [x 5])
Getting Invalid operator.
Appreciate your help. Thank you all for your time.