如何在方案中添加嵌入列表?

时间:2013-03-23 16:48:16

标签: list recursion functional-programming lisp scheme

我试图在方案中生成一个符号表,而我却停留在设置符号函数上。 该数字对应于代码的块级别或"范围"。

First symbol it reads in
((c class 0))
Next symbols 
(((c class 0) (a int 0) (b float 0)))
We read a bracket and read the next variables to a new scope.
(((a char 1) (d int 1)) ((c class 0) (a int 0) (b float 0)))
We leave that scope and "pop the stack".
(((c class 0) (a int 0) (b float 0)))

如何始终添加范围内第一个列表的最深列表?

1 个答案:

答案 0 :(得分:1)

我怀疑你最好不要使用不同的代表。许多人中的一个将是:

(define (make-symbol-table parent alist)
  `(SYMBOL-TABLE ,parent ,@alist))
(define symbol-table-parent cadr)
(define symbol-table-alist  cddr)

(define (symbol-table-depth table)
  (let ((parent (symbol-table-parent table)))
    (if (not parent)
        1
        (+ 1 (symbol-table-depth parent))))

(define (symbol-table-lookup table name)
  (cond ((assoc name (symbol-table-alist table)) => cdr)
        (else (let ((parent (symbol-table-parent table)))
                (and parent (symbol-table-lookup parent name))))))