String 如何在Clojure(脚本)中生成这些字符串匹配函数?
考虑以下多行字符串String 如何在Clojure(脚本)中生成这些字符串匹配函数?,string,clojure,clojurescript,String,Clojure,Clojurescript,考虑以下多行字符串S: apple banana berry cantelope 我正在尝试编写/定位clojure函数,我将在本文或match和和match中调用这些函数。以下是他们应该做的一些例子: (or-match S "apple" "berry") ;; should return the two line string: ;; apple ;; banana berry (and-match S "apple" "berry") ; should return nil (a
S
:
apple
banana berry
cantelope
我正在尝试编写/定位clojure函数,我将在本文或match
和和match
中调用这些函数。以下是他们应该做的一些例子:
(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(脚本)中生成此类函数?您可以检查每个/任何候选对象是否以字符串形式出现:
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
vsevery?
),您可以将其概括为:
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")
这没有什么问题,但我很好奇为什么你在haskell和clojure标签上都问同样的问题。试图决定使用哪种语言来完成一项任务,或者其他什么?是的——我正在比较这两种语言如何处理这个问题。我已经用一种不同的方法在clojure中构建了一些东西,并且正在切换到Haskell(对我来说是一种新的语言),我希望使用这种更好的技术(比较解决方案在每种语言中的外观!)