簡體   English   中英

解析Scheme中的具體語法

[英]Parsing concrete syntax in Scheme

我寫了一個程序,獲取減法的有效前綴列表(例如,“( - 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))))

它在邏輯上工作得很好,但我不理解打印中縮進的邏輯。 輸入:

(parse-prefix'( - - 1 2 - 3 - 4 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)))

雖然我想要以下打印樣式:

  #(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基於結構打印的方式)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM