gengns ES

An entry from the gengns log, written by Génesis García Morilla · · JavaScript

Basic LISP Parser

Have you ever think about analysing the syntax of another computer language to use it in the one you are working with? We are going to transform a valid LISP expression (string) into a JavaScript object.

JavaScript

const parser = str => {
  let count = 0
  let arr = []
  let atom = []
  // Prepare array with atoms
  for (const s of str.slice(1, -1).split(' ')) {
    atom.push(s)
    if (s.includes('(')) count += s.match(/\(/g).length
    if (s.includes(')')) count -= s.match(/\)/g).length
    if (count == 0) {
      arr.push(atom.join(' '))
      atom = []
    }
  }
  // If atom with no brackets add in other case recursion
  return arr.reduce((obj, s, i) => {
    if (s.includes('(')) obj[`l${i}`] = parser(s)
    else obj[`l${i}`] = s
    return obj
  }, {})
}

// Examples (only valid expressions)
document.body.innerHTML =
['(a b c)', '(a b (c d (e)) (f))', '(a bc (d (ef) g) (hi))'].map(str => {
  const obj = parser(str)
  console.log(str)
  console.log(obj)
  return `<strong>${str}</strong> = <mark>${JSON.stringify(obj)}</mark>`
}).join('<br>')
Open in JSFiddle

Homeworks: check if it’s a valid LISP expression.

Tags: LISP, parser, recursion