Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

(defn substring? 
  "is 'sub' in 'str'?"
  [sub str] 
  (if (not= (.indexOf str sub) -1) 
    true 
    false))
share|improve this question
    
hmmm...just discovered - (.contains "abcdefghi" "abc"), anyway that doesn't interop with Java (purely out of curiosity!)? –  decentralised Oct 31 '13 at 13:01
1  
a re-find might be the simplest way. The old contrib.string used .contains as well so it was probably the best tool for the job. –  georgek Nov 1 '13 at 0:24

1 Answer 1

up vote 6 down vote accepted

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

(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))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.