John Horus
John Horus

Reputation: 45

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.

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.

Upvotes: 2

Views: 725

Answers (1)

Aleph Aleph
Aleph Aleph

Reputation: 5395

filter expects a one-argument function. 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)

Upvotes: 3

Related Questions