Skip to content

Instantly share code, notes, and snippets.

@gilesbowkett
Last active August 29, 2015 14:20
Show Gist options
  • Save gilesbowkett/b18af441e81747f10143 to your computer and use it in GitHub Desktop.
Save gilesbowkett/b18af441e81747f10143 to your computer and use it in GitHub Desktop.
what's the best way to satisfy this Midje test?
(facts "about finding sub-words"
(fact "(sub-words) finds all possible sub-words"
(sub-words "monocarp") => ["mono",
"monoc",
"monoca",
"monocar",
"onoc",
"onoca",
"onocar",
"onocarp",
"noca",
"nocar",
"nocarp",
"ocar",
"ocarp",
"carp"]))
@hotwoofy
Copy link

There are more efficient ways to do it that just iterate over the correct bounds, but I quite like:

(defn sub-words
  ([^String s] (sub-words s 4))
  ([^String s ^Integer min-length]
   (vec (for [start (range 0 (.length s))
              length (range min-length (.length s))
              :let [end (+ start length)]
              :when (<= end (.length s))]
          (subs s start end)))))

@hotwoofy
Copy link

But even in your example, if you find yourself filtering the results of a for then you might sometimes look at using :let and :when.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment