使用Scheme解析字符串

我正在尝试编写一个简单的解析器,它从字符串创建一个sxml-expression,e. G.

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

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

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

(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)))))

评估(解析序列my-sequence)得到(“this”(“是”“a”)).已创建嵌套表达式,但程序已完成,但未评估最后一项“test”.问题是,如何从get-subsequence返回到解析序列?

感谢任何帮助,非常感谢提前! 🙂

最佳答案 要解决您的初始问题,如何返回多个值:使用“值”表单.下面是一个示例实现,其中内部过程返回要处理的剩余列表和到目前为止的结果.它在开头括号上进行了说明.

(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")
点赞