Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter type String in Clojure

Tags:

filter

clojure

Currently I'm trying to learn Clojure and I would like to write a function that has a variable amount of parameters. This function should filter every input to check if it's a string or not. If it does, every input of type string should be returned..

Clojure is hard for me and different way of thinking, but am I on the right direction here.. I can't seem to solve it:

(defn returnString [& y]
(if (next y)
(filter (fn [x] (= (type x) "java.lang.String"))y)
(recur (next x))))

Thanks!

like image 931
Mittchel Avatar asked May 12 '12 23:05

Mittchel


1 Answers

There is a function called string? that returns true if the argument is a string, or false if not.

=> (string? "hi")
true
=> (string? 100)
false
=> (string? ["a" "b" "c"])
false

So with that in mind, your function would look like:

(defn return-strings [& vals]
  (filter string? vals))

The filter function will return a sequence (essentially a collection) of values, so there is no need worry about recursion (that is, using recur) in your custom function for this case.


The anonymous function you use to determine what is a string is very close to being correct. If you take a look at the source for string? by entering (source string?) into your REPL, you'll see:

(fn [x] (instance? String x))

Although, the approach you are taking would work as well. You just need to specify the String class instead of the string value you were giving. (Note, you can leave off java.lang because that package is automatically included just like it is in Java.)

(fn [x] (= (type x) String))
like image 159
Jeremy Avatar answered Oct 02 '22 14:10

Jeremy