我以前见过这样的图书馆,但后来却忘记了它的名字.
您可以指定匹配列表中元素的模式,类似于以下行:
(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
Run Code Online (Sandbox Code Playgroud)
如果我完全想象这一点,有人可以阐明一个人如何写出这些东西吗?
更一般地说,您需要一种表达方式来解析序列。当然,Clojure 有很多解析库,但其中许多都通过解析完成了词法分析(在优化性能方面可能有充分的理由),因此只能在字符串上使用。您可能必须在工具箱之外寻找一个允许词法分析作为单独关注点的解析器。
以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))
Run Code Online (Sandbox Code Playgroud)
现在定义您的模式
(def odds-and-evens (>> (many (token odd?)) (times 2 (token even?))))
Run Code Online (Sandbox Code Playgroud)
并测试
(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
Run Code Online (Sandbox Code Playgroud)
从这里您可以添加糖来根据需要指定您的图案。