【发布时间】:2023-03-21 03:10:01
【问题描述】:
我正在尝试对列表进行模式匹配,但由于某种原因,当我执行以下操作时,我得到了意外的匹配:
> (define code '(h1 ((id an-id-here)) Some text here))
> (define code-match-expr '(pre ([class brush: python]) ...))
> (match code
[code-match-expr #t]
[_ #f])
#t
问题:为什么code 匹配code-match-expr?
实际用例
我在 Racket REPL 中尝试过这个,因为我实际上想解决另一个实际问题:使用 Pollen 的 pygments 包装函数来突出显示代码,稍后将输出为 HTML。为此,我编写了以下代码,出现问题的地方:
(define (read-post-from-file path)
(Post-from-content (replace-code-xexprs (parse-markdown path))))
(define (replace-code-xexprs list-of-xexprs)
;; define known languages
(define KNOWN-LANGUAGE-SYMBOLS
(list 'python
'racket
'html
'css
'javascript
'erlang
'rust))
;; check if it matches for a single language's match expression
;; if it mathces any language, return that language's name as a symbol
(define (get-matching-language an-xexpr)
(define (matches-lang-match-expr? an-xexpr lang-symbol)
(display "XEXPR:") (displayln an-xexpr)
(match an-xexpr
[`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
[`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
[_ #f]))
(ormap (lambda (lang-symbol)
;; (display "trying to match ")
;; (display an-xexpr)
;; (display " against ")
;; (displayln lang-symbol)
(matches-lang-match-expr? an-xexpr lang-symbol))
KNOWN-LANGUAGE-SYMBOLS))
;; replace code in an xexpr with highlightable code
;; TODO: What happens if the code is in a lower level of the xexpr?
(define (replace-code-in-single-xexpr an-xexpr)
(let ([matching-language (get-matching-language an-xexpr)])
(cond [matching-language (code-highlight an-xexpr matching-language)]
[else an-xexpr])))
;; apply the check to all xexpr
(map replace-code-in-single-xexpr list-of-xexprs))
(define (code-highlight language code)
(highlight language code))
在本例中,我正在解析一个包含以下内容的降价文件:
# Code Demo
```python
def hello():
print("Hello World!")
```
我得到以下xexprs:
1.
(h1 ((id code-demo)) Code Demo)
2.
(pre ((class brush: python)) (code () def hello():
print("Hello World!")))
但是,由于某种原因,这些都不匹配。
【问题讨论】:
标签: list pattern-matching racket ellipsis