*Simple question : Why does this function throw an exception when evaluated ? *
-
In the case where there is a duplicate in the string , there is a Class cast exception thrown upon finding the duplicate.
-
In the case where the string has no duplicates, a NullPointerException is thrown.
*The Code *
(defn first-duplicate-char [str-in]
(loop [list-Rem (seq str-in) set-Seen (set [])]
(print (type list-Rem) " " list-Rem (next list-Rem) "\n")
(if (= 0 (count str-in))
nil
(if (some #(= (first list-Rem) %) set-Seen)
(first list-Rem)
(recur
(seq (next list-Rem))
(conj set-Seen (first list-Rem)))))))
Your problem is that
(= 0 (count str-in))never changes, so you eventually try to callfirstonnil. [EDIT: I’m wrong, your code actually works as is — that if statement is just a no-op. I hope you enjoy the rest of this answer anyway.]Instead, you should be calling
next(notrest) onlist-Remin therecurand usinglist-Remdirectly in theiftest, using the property ofnextthat returns nil for an empty seq. Here’s how I would rewrite your code:Changes:
seqon the output ofnextorrestcontains?(check for existence of key) is faster thansome(run a predicate on elements until something yields a truthy value)whento returnnilon test failurewhen-letto destructure and bind first char and restStylistic changes: