9
\$\begingroup\$

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))
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Oct 31, 2013 at 12:33
\$\endgroup\$
2
  • \$\begingroup\$ hmmm...just discovered - (.contains "abcdefghi" "abc"), anyway that doesn't interop with Java (purely out of curiosity!)? \$\endgroup\$ Commented Oct 31, 2013 at 13:01
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Nov 1, 2013 at 0:24

1 Answer 1

10
\$\begingroup\$

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))
answered Nov 10, 2013 at 22:46
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.