Fork me on GitHub
#javascript
<
2023-06-14
>
finchharold18:06:39

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.