I'm wondering if it's possible to do a pass on parsing of a define
expression in lisp with a single regular expression, for example with the following input:
#lang sicp
(define (square x) (* x x))
(define (average x y) (/ (+ x y) 2))
; using block scope
(define (sqrt x)
; x is always the same -- "4" or whatever we pass to it, so we don't need that
; in every single function that we define, we can just inherit it from above.
(define (improve guess) (average guess (/ x guess)))
(define (good-enough? guess) (< (abs (- (square guess) x)) 0.001 ))
(define (sqrt-iter guess) (if (good-enough? guess) guess (sqrt-iter (improve guess))))
(sqrt-iter 1.0)
)
(sqrt 4)
I would want to highlight the three procedures below (none of the function-scoped procedures) that start with define
. The process I was thinking (if I were to do it iteratively) would be:
- Remove comments.
- Grab the start of the define with
\(\s*define
- Consume balanced parentheses up until the unbalanced
)
that finishes our procedure. For a regex, something like:(?:\([^)]*\))*
, though I'm sure it gets much more complex with the greediness of the*
's.
And this wouldn't even be taking into account I could have a string "( define )"
that we'd also want to ignore.
Would it be possible to build a regex for this, or too complicated? Here is my starting point, which is a long way from complete: https://regex101.com/r/MlPmOd/1.