Skip to content

Instantly share code, notes, and snippets.

@ryanbaldwin
Last active October 2, 2015 21:31
Show Gist options
  • Save ryanbaldwin/f9984c9c017e753f2095 to your computer and use it in GitHub Desktop.
Save ryanbaldwin/f9984c9c017e753f2095 to your computer and use it in GitHub Desktop.
A solution to the classic "Find the index-of the first occurrence of substring in a string" problem, written in Clojure.
(ns ward.index-of)
(defn index-of
"Returns the first index where needle is found in haystack.
Returns -1 if the needle is not found in haystack."
[needle haystack]
(loop [n needle h haystack index 0]
(let [n-length (count n)
h-length (count h)]
(cond
(> n-length h-length) -1
(= n (subs h 0 n-length)) index
:else (recur n (subs h 1) (inc index))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment