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!
There is a function called
string?that returns true if the argument is a string, or false if not.So with that in mind, your function would look like:
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: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.langbecause that package is automatically included just like it is in Java.)