DEV Community

Discussion on: 20-line DSL in typescript or js without a library

Collapse
 
rxliuli profile image
rxliuli

I've been learning sicp recently and have therefore built a simple lisp interpreter and runtime, the implementation is about 300 lines long. The parsing part is ugly because I haven't optimized it using a strategy pattern similar to the one above.
Finally I was able to run the code, all code refer to the gists link below

expect(evalLisp(parseLisp('("liuli")'))).toBe('liuli')
expect(evalLisp(parseLisp('(+ 1 2)'))).toBe(3)
expect(evalLisp(parseLisp('(+ 1.1 3.3)'))).toBe(4.4)
expect(evalLisp(parseLisp('(true)'))).toBe(true)
expect(evalLisp(parseLisp('(begin (define x 1) (define y 2) (+ x y))'))).toBe(3)
expect(evalLisp(parseLisp('(if (true) 0 1)'))).toBe(0)
expect(evalLisp(parseLisp('(if (false) 0 1)'))).toBe(1)
expect(evalLisp(parseLisp('(cond (false 0) (false 1))'))).toBe(null)
expect(evalLisp(parseLisp('(cond (false 0) (false 1) (else 2))'))).toBe(2)
expect(evalLisp(parseLisp('(cond (false 0) (true 1) (else 2))'))).toBe(1)
expect(evalLisp(parseLisp('((lambda (x y) (+ x y)) 1 2)'))).toBe(3)
expect(evalLisp(parseLisp('(begin (define (add x y) (+ x y)) (add 1 2))'))).toBe(3)
expect(
  evalLisp(
    parseLisp(`
  (
    begin
    (define (cons a b) (
      lambda (action) (
        cond
        ((= action "car") a)
        ((= action "cdr") b)
      )
    ))
    (define (car cons) (cons "car"))
    (define (cdr cons) (cons "cdr"))
    (define v (cons 1 2))
    (+ (car v) (cdr v))
  )
`),
  ),
).toBe(3)
Enter fullscreen mode Exit fullscreen mode

gist.github.com/rxliuli/9ee90a7ce7...