Last active
October 2, 2015 21:31
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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