patternModerate
Clojure - substring? function
Viewed 0 times
substringfunctionclojure
Problem
Trying to write a substring function in Clojure. I am sure there is a more idiomatic way. Can anyone enlighten me?
Otherwise, here is my version. Thoughts?
Otherwise, here is my version. Thoughts?
(defn substring?
"is 'sub' in 'str'?"
[sub str]
(if (not= (.indexOf str sub) -1)
true
false))Solution
As you wrote in your comments, (.contains "str" "sub") is perfectly fine. it is indeed java interop - it runs the method contains on String object "str".
two more comments, first, passing str as a var name isnt so good, since str is a function, so you should consider giving it a different name. Second, in your implementation, its quite redundant to write
You could simply write
two more comments, first, passing str as a var name isnt so good, since str is a function, so you should consider giving it a different name. Second, in your implementation, its quite redundant to write
(defn substring? [sub st]
(if (not= (.indexOf st sub) -1)
true
false))You could simply write
(defn substring? [sub st]
(not= (.indexOf st sub) -1))Code Snippets
(defn substring? [sub st]
(if (not= (.indexOf st sub) -1)
true
false))(defn substring? [sub st]
(not= (.indexOf st sub) -1))Context
StackExchange Code Review Q#33577, answer score: 10
Revisions (0)
No revisions yet.