简体   繁体   English

Clojure:将过滤器与具有多个参数的函数一起使用

[英]Clojure: Using filter with a function that has more than one parameter

I'm trying to find all values within a collection that start with one letter. 我正在尝试查找集合中以一个字母开头的所有值。 Filter seems to be the quickest way to do that. 过滤器似乎是最快的方法。 But I'm having trouble getting it to work with two parameters. 但是我很难让它与两个参数一起使用。

This is the function 这是功能

(defn starts [letter word]
  (def startVal (clojure.string/starts-with? word letter)
  startVal)

That's fine. 没关系。 It's trying to use filter on that that's the problem. 它试图在那上面使用过滤器。 I need to be able to try more than one letter, so I can't just hard-code it into the function here. 我需要能够尝试多个字母,所以我不能仅仅将其硬编码到此处的函数中。 But filter always throws errors (wrong arity (3) when I try to feed it more than one value. 但是filter总是会抛出错误(当我尝试向其提供多个值时,错误的arity(3)。

When I change starts into a one parameter function (I pass just the word and then I hardcode in a letter) and try 当我开始更改为一个参数函数时(我只传递单词,然后以字母硬编码),然后尝试

(println (filter starts [this is my example collection of words])

It works and I get the right value. 它有效,我得到了正确的价值。

How do I get filter to use two values. 如何获得过滤器以使用两个值。 would it be doable via anonymous function written right into the filter call? 通过直接写到过滤器调用中的匿名函数可以做到吗?

If I'm going about this all wrong and could just code it another way I'd be happy to know too, but I would like to figure out how to use filter this way, if there is a solution. 如果我要解决所有这些错误,并且也可以以另一种方式编写代码,我也很高兴知道,但是如果有解决方案,我想弄清楚如何以这种方式使用过滤器。

filter expects a one-argument function. filter需要一个参数的函数。 You can use an anonymous one-argument wrapper function if one of the arguments stays constant: 如果参数之一保持不变,则可以使用匿名的一参数包装器函数:

(filter #(starts my-letter %) my-words)

Or, equivalently: 或者,等效地:

(filter (partial starts my-letter) my-words)

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

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