简体   繁体   English

在Clojure函数中移动参数

[英]Move parameter in Clojure function

I'm working on 4clojure problem 29 : "Get the Caps" 我正在研究4clojure问题29: “搞定问题

(= (__ "HeLlO, WoRlD!") "HLOWRD")

I've written a solution in the REPL: 我在REPL中写了一个解决方案:

user=> (apply str (filter (fn [foo] (some #(= % foo) 
         (map char (range 65 91)))) "AbC"))
"AC"

But as you can see my parameter "AbC" is nested two parentheses in. How would I move my parameter to the outside so I can use it in the 4clojure test? 但是正如你可以看到我的参数“AbC”嵌套在两个括号中。我如何将我的参数移到外面以便我可以在4clojure测试中使用它? Have I approached the problem in the wrong way? 我是否以错误的方式解决了问题?

You don't need to move the a parameter to the outside, you can just use the same technique you used to create the filtering function, that is, with fn : 您不需要将a参数移动到外部,您可以使用与创建过滤函数相同的技术,即使用fn

(fn [string] 
  (apply str 
    (filter 
      (fn [foo] (some #(= % foo) (map char (range 65 91)))) 
      string)))

As an example of this, the following two statements are the same: 作为一个例子,以下两个语句是相同的:

(+ 1 2 3)
((fn [n] (+ 1 2 n)) 3)

However, to actually answer your question, you could use comp ("compose") and partial to move the parameter to allow eta conversion (that is the technical name for the last part of the manipulation you are attempting to do): 但是,要实际回答您的问题,您可以使用comp (“compose”)和partial来移动参数以允许eta转换 (这是您尝试执行的操作的最后部分的技术名称):

(comp (partial apply str)
      (partial filter (fn [foo] (some #(= % foo) 
                                       (map char (range 65 91))))))

This expression is now a function that takes a string, filters the capital letters and then converts it back to a string (notices that comp applies functions from right to left). 此表达式现在是一个函数,它接受一个字符串,过滤大写字母然后将其转换回字符串(通知comp从右到左应用函数)。

(NB, that last expression probably isn't very idiomatic Clojure; the first method, or one of the suggestions of others, is better.) (注意,最后一个表达可能不是非常惯用的Clojure;第一种方法,或者其他人的建议之一,更好。)

You should pass a function as a solution. 您应该将函数作为解决方案传递。 Something like: 就像是:

(fn [text] 
    (apply str (filter (fn [foo] (some #(= % foo) 
                                        (map char (range 65 91)))) 
                       text)))

Also you can use Character.isUpperCase to filter all upper case chars: (filter (fn [ch] (Character/isUpperCase ch) text) 您还可以使用Character.isUpperCase过滤所有大写字符: (filter (fn [ch] (Character/isUpperCase ch) text)

I'm not familiar with 4Clojure, but if it's allowed, you could use clojure.string/replace . 我不熟悉4Clojure,但是如果允许的话,你可以使用clojure.string/replace

The following should do the trick: 以下应该做的伎俩:

(fn [s] (clojure.string/replace s #"[^A-Z]" ""))

Everything that isn't in the range A to Z is replaced with the empty string. 不在A到Z范围内的所有内容都将替换为空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM