I am trying to define a recursive function balanced
that takes a string and returns true only if the parens in the string are balanced.
The elisp code I wrote is based on some Scala code I wrote for the Coursera class by Odersky, it's a transliteration.
;; check if expr (list of chars of some expression) is balanced
(defun balanced (expr)
(defvar lparen (string-to-char "("))
(defvar rparen (string-to-char ")"))
(defun is-open (c) (eq lparen c))
(defun is-close (c) (eq rparen c))
(defun is-empty (ls) (eq ls nil))
(defun is-matching (l r) (and (is-open l) (is-close r)))
(defun is-balanced (list stack)
(cond ((is-empty list) (is-empty stack))
((is-open (car list))
(is-balanced (cdr list) ;; 'push' open-paren onto stack
(cons (car list) stack)))
((is-close (car list))
(if (is-empty stack) nil
(and
(is-balanced (cdr list) (cdr stack))
(is-matching (car stack) (car list)))))
(is-balanced (cdr list) (cdr stack))))
is-balanced
I am in lisp-interaction-mode, so I used Ctrl-J to evaluate the above defun
statement.
Then, when I attempt to evaluate this:
(balanced "(balanced nil nil)")
I get a void-variable error:
Debugger entered--Lisp error: (void-variable is-balanced)
balanced("(balanced nil nil)")
(progn (balanced "(balanced nil nil)"))
eval((progn (balanced "(balanced nil nil)")) t)
eval-last-sexp-1(t)
eval-last-sexp(t)
eval-print-last-sexp()
call-interactively(eval-print-last-sexp nil nil)
recursive-edit()
debug(error (void-variable is-balanced))
balanced("(balanced nil nil)")
(progn (balanced "(balanced nil nil)"))
eval((progn (balanced "(balanced nil nil)")) t)
eval-last-sexp-1(t)
eval-last-sexp(t)
eval-print-last-sexp()
call-interactively(eval-print-last-sexp nil nil)
recursive-edit()
The function doesn't seem to recognize itself, what am I doing wrong?