如何在Clojure(Script)中创建这些字符串匹配函数?

时间:2016-04-28 21:28:32

标签: string clojure clojurescript

考虑以下多行字符串S

apple
banana berry
cantelope

我正在尝试编写/查找我将在此帖or-matchand-match中调用的clojure函数。以下是他们应该做的一些例子:

(or-match S "apple" "berry")

;; should return the two line string:
;; apple
;; banana berry

(and-match S "apple" "berry") ; should return nil

(and-match S "banana berry") ; should return a single line containing "banana berry"

如何在clojure(脚本)中创建这样的函数?

1 个答案:

答案 0 :(得分:2)

您可以检查字符串中是否存在每个/任何候选者:

user> (defn or-match [s & items]
        (filter (fn [line]
                  (some #(clojure.string/includes? line %)
                        items))
                (clojure.string/split-lines s)))
#'user/or-match

user> (or-match "apple\nbanana berry\ncantelope"
                "apple" "berry")
("apple" "banana berry")

user> (defn and-match [s & items]
        (filter (fn [line]
                  (every? #(clojure.string/includes? line %)
                          items))
                (clojure.string/split-lines s)))
#'user/and-match

user> (and-match "apple\nbanana berry\ncantelope"
                 "apple" "berry")
()

user> (and-match "apple\nbanana berry\ncantelope"
                 "banana berry")
("banana berry")

由于这些函数只有一个函数(some vs every?)不同,因此可以概括它:

user> (defn get-lines-matcher [check]
        (fn [s & items]
          (filter (fn [line]
                    (check #(clojure.string/includes? line %) items))
                  (clojure.string/split-lines s))))
#'user/get-lines-matcher

user> (def and-match (get-lines-matcher every?))
#'user/and-match

user> (def or-match (get-lines-matcher some))
#'user/or-match

user> (or-match "apple\nbanana berry\ncantelope"
                "apple" "berry")
("apple" "banana berry")

user> (or-match "apple\nbanana berry\ncantelope"
                "apple" "berry")
("apple" "banana berry")

user> (and-match "apple\nbanana berry\ncantelope"
                 "apple" "berry")
()

user> (and-match "apple\nbanana berry\ncantelope"
                 "banana berry")
("banana berry")

user> (and-match "apple\nbanana berry\ncantelope"
                 "banana" "berry")
("banana berry")