解析方案中的具体语法

问题描述:

我编写了一个程序,用于获取用于减法的有效前缀列表(例如,我们知道的“6-5”)(例如“( - 6 5)”)。这是我的代码:解析方案中的具体语法

(define parse-diff-list 
(lambda (datum) 
(cond 
    ((number? datum) (const-exp datum)) ;; if datum is a number, return const-exp 
    ((pair? datum)      ;; if datum is a pair: 
    (let ((sym (car datum)))    ;; let sym be the first of the pair 
     (cond 
     ((eqv? sym '-)       ;; if sym is minus: 
     (let ((lst1 (parse-diff-list (cdr datum)))) ;; parse second element of subtraction 
     (let ((lst2 (parse-diff-list (cdr lst1)))) ;; parse first element of subtraction 
      (cons (diff-exp (car lst1) (car lst2)) (cdr lst2))))) ;; "perform" the subtraction 
     ((number? sym)       ;; if sym is number: 
     (cons (const-exp sym) (cdr datum))) ;; return const-exp with the remainder of the list, yet to be processed 
     (else (eopl:error 'parse-diff-list "bad prefix-expression, expected - ~s" sym))))) 
    (eopl:error 'parse-diff-list "bad prefix-expression ~s" datum)))) 

(define parse-prefix 
    (lambda (lst) 
    (car (parse-diff-list lst)))) 

它在逻辑上工作正常,但我不明白打印中的缩进逻辑。对于输入:

(分析前缀“( - - 1 2 - 3 - 45))

它打印:

#(struct:diff-exp 
    #(struct:diff-exp #(struct:const-exp 1) #(struct:const-exp 2)) 
    #(struct:diff-exp #(struct:const-exp 3) #(struct:diff-exp #(struct:const-exp 4) #(struct:const-exp 5))) 

虽然我想下列打印风格:

#(struct:diff-exp 
    #(struct:diff-exp 
     #(struct:const-exp 1) 
     #(struct:const-exp 2)) 
    #(struct:diff-exp 
     #(struct:const-exp 3) 
     #(struct:diff-exp 
     #(struct:const-exp 4) 
     #(struct:const-exp 5))) 

这不是对我来说是小问题多,因为它创建缺口,但我不知道它是怎么做的。

非常感谢!

看看racket/pretty漂亮的打印库。

尤其注意参数(pretty-print-columns)这 你可以这样设置:为了避免排长队

`(pretty-print-columns 40)` 

http://docs.racket-lang.org/reference/pretty-print.html

(我猜你正在使用基于结构的印刷方式DrRacket)

+0

比是一个可能的想法(确实使用DrRacket),但什么原因造成现在执行的缺口(不我使用任何特定的印刷风格)? – avish12