我认为您正在寻找解析使用 BNF 语法编写的文件,并生成一个 s 表达式版本;是对的吗?
如果是这样,那应该不难。特别是,您的问题所暗示的格式是每一行的形式
<NT> :: = [<NT>|<T>]*
...你可以像这样拆开:
#lang racket
;; COPYRIGHT 2012 John B. Clements (clements@brinckerhoff.org)
;; Licensed under the Apache License, version 2.
;; (You're free to use it, but your source code has to include
;; my authorship.)
(require rackunit)
(define example
(list "S ::= ba"
"B ::= a"
"C ::= SB"))
;; parse a single line:
;; string -> (list/c symbol? (listof (or/c string? symbol?)))
(define (parse-line l)
(match (regexp-match #px"^([A-Z]) ::= ([A-Za-z]*)$")
[(list _ lhs rhses)
(list lhs (map parse-char (string->list rhses)))]))
;; parse a single char:
;; char -> (or/c symbol? string?)
(define (parse-char ch)
.. oops! out of time. You'll have to write this part yourself... )
(check-expect (map parse-line example)
'((S ("b" "a"))
(B ("a"))
(C (S B))))
哎呀!我看到那里有一个错误。没问题,你会想办法的。得跑了……