2017-04-09 59 views
1

我編寫了一個程序,用於獲取用於減法的有效前綴列表(例如,我們知道的「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))) 

這不是對我來說是小問題多,因爲它創建缺口,但我不知道它是怎麼做的。

非常感謝!

回答

0

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

尤其注意參數(pretty-print-columns)這 你可以這樣設置:爲了避免排長隊

`(pretty-print-columns 40)` 

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

(我猜你正在使用基於結構的印刷方式DrRacket)

+0

比是一個可能的想法(確實使用DrRacket),但什麼原因造成現在執行的缺口(不我使用任何特定的印刷風格)? – avish12