gpt4 book ai didi

clojure - 用于列表项通用匹配的正则表达式样式匹配库

转载 作者:行者123 更新时间:2023-12-04 15:34:12 30 4
gpt4 key购买 nike

我以前见过这样的图书馆,但后来忘记了它叫什么。

您可以指定与列表中的元素匹配的模式,类似于:

(def oddsandevens (pattern (n-of odd? :*) (n-of even? 2) :$))

(pattern-match oddsandevens [1 1 2 2]) => true
(pattern-match oddsandevens [1 1 1 2 2]) => true

(pattern-match oddsandevens [1 1 2 2 2]) => false
(pattern-match oddsandevens [1 1 2]) => false

如果我完全想象这一点,有人可以阐明如何写这些东西之一吗?

最佳答案

更一般地说,您正在寻求一种富有表现力的方式来解析序列。 Clojure 当然有很多解析库,但其中有很多 complect带有解析的词法分析(在优化性能方面可能有充分的理由),因此只能用于字符串。您可能需要查看 toolbox 之外的内容。找到一个允许将词法分析作为单独关注点的解析器。

举个例子,The Parsatron (仅重 262 loc)

(require '[the.parsatron ; sampling of available combinators 
:refer [run token attempt many times choice always never >> eof]])

(defn matches? [parser input]
(run
(choice
(attempt (>> parser (eof) (always true)))
(always false))
input))

现在定义你的模式
(def odds-and-evens (>> (many (token odd?)) (times 2 (token even?))))

并测试
(matches? odds-and-evens [1 1 2 2])   ;=> true
(matches? odds-and-evens [1 1 1 2 2]) ;=> true
(matches? odds-and-evens [1 1 2 2 2]) ;=> false
(matches? odds-and-evens [1 1 2]) ;=> false

从这里您可以添加糖以根据需要指定您的模式。

关于clojure - 用于列表项通用匹配的正则表达式样式匹配库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23119833/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com