加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 02:30:28 所属栏目:百科 来源:网络整理
导读:我以前见过这样的图书馆,但后来却忘记了它的名字. 您可以指定匹配列表中元素的模式,类似于以下行: (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])
我以前见过这样的图书馆,但后来却忘记了它的名字.

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

(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之外寻找一个解析器,它允许lexing作为一个单独的关注点.

以The Parsatron(仅重262位)为例

(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

从这里你可以添加糖来根据需要指定你的模式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读