4

我正在尝试编写一个简单的解析器,它从字符串创建一个 sxml 表达式,例如

"This is a [Test]" ===> (item "This is a" (subitem "Test"))

任何想知道给定示例中的方括号的人都可以查看所谓的Leiden 约定

这是我到目前为止写的代码:

(define my-sequence '("this" "[" "is" "a" "]" "test"))

(define (left-square-bracket? item)
  (or (equal? item "[")
      (eq? item #\x005b)))

(define (right-square-bracket? item)
  (or (equal? item "]")
      (eq? item #\x005d)))

(define (parse-sequence sequence)
  (cond ((null? sequence) '())
        ((left-square-bracket? (car sequence))
         (let ((subsequence (get-subsequence (cdr sequence))))
           (list subsequence)))
        (else
         (cons (car sequence)
               (parse-sequence (cdr sequence))))))

(define (get-subsequence sequence)
  (if (right-square-bracket? (car sequence))
      '()
      (cons (car sequence)
            (get-subsequence (cdr sequence)))))

评估(parse-sequence my-sequence)产量("this" ("is" "a"))。已创建嵌套表达式,但程序在未计算最后一项的情况下完成"test"。问题是,我如何从get-subsequenceto返回parse-sequence

任何帮助表示赞赏,非常感谢提前!:)

4

2 回答 2

2

要解决您最初的问题,如何返回多个值:使用“值”表单。这是一个示例实现,其中内部过程返回要处理的剩余列表和到目前为止的结果。它在左括号上递归。

(define (parse-sequence lst)

  (define (parse-seq lst)
    (let loop ((lst lst) (res null))
      (cond
        ((null? lst) (values null res))
        ((string=? (car lst) "[")
         (let-values ([(lst2 res2) (parse-seq (cdr lst))])
           (loop lst2 (append res (list res2)))))
        ((string=? (car lst) "]")
         (values (cdr lst) res))
        (else
          (loop (cdr lst) (append res (list (car lst))))))))

  (let-values ([(lst res) (parse-seq lst)])
    res))

然后

(parse-sequence '("this" "is" "a" "test"))
(parse-sequence '("this" "[" "is" "a" "]" "test"))
(parse-sequence '("this" "[" "is" "[" "a" "]" "]" "test"))

将产生

'("this" "is" "a" "test")
'("this" ("is" "a") "test")
'("this" ("is" ("a")) "test")
于 2012-11-18T18:46:12.447 回答
0

我通过open-input-string结合使用取得了一些进展read-char:

(define my-sequence (open-input-string "this [is a] test"))

(define (parse-sequence sequence)
  `(item
    ,@(let loop ((next-char (read-char sequence)))
        (cond ((eof-object? next-char) '())
              ((left-square-bracket? next-char)
               (let ((subsequence (get-subsequence sequence)))
                 (cons subsequence
                       (loop (read-char sequence)))))
              (else
               (cons next-char
                     (loop (read-char sequence))))))))

(define (get-subsequence sequence)
  `(subitem
    ,@(let loop ((next-char (read-char sequence)))
        (if (right-square-bracket? next-char)
            '()
            (cons next-char
                  (loop (read-char sequence)))))))

(parse-sequence my-sequence)
===> (item #\t #\h #\i #\s #\space (subitem #\i #\s #\space #\a) #\space #\t #\e #\s #\t)

现在工作还在继续,一步一步地进行。:)

任何意见和建议仍然受到赞赏。:)

于 2012-11-17T22:31:07.263 回答