On Apr 4, 2009, at 6:18 PM, Mark Triggs wrote:
> > Hi David, > > Quite a few times when I've felt the need for this sort of thing I've > found that laziness comes to the rescue. Would something like this > sort of approach work for you? > > (defn possibilities [word pos] > "All variations of `word' with letters from 'a' to 'z' inserted at > `pos'" > (let [[beg end] (split-at pos word) > letters (map char (range (int \a) (inc (int \z))))] > (map #(apply str (concat beg [%] end)) letters))) > > (defn all-possibilities [word] > (for [n (range (inc (count word))) > pos (possibilities word n)] > pos)) > > ;; Since all-possibilities produces a lazy seq we don't need short > circuiting anyway... > (some #(binary-search word) (all-possibilities "hello")) > > Mark and Jim, Thanks for your responses. You both make an excellent point about functional code not often needing explicit loops (and even being a sign of design problems). My example is decidedly non-functional (I don't really like that term...My code works--it does function! :-) ). It was kind of a first cut in a more imperative style because I thought it might be more efficient destructively modifying a char array rather than copying lots of substrings. I intended to attempt a more functional version next. I was more curious about the general case, but you guys may be right that nested loops just aren't needed. Your example looks useful, Mark. In fact, for the real program I do want to collect all possible suggestions rather than terminating with the first one. So I'll be dealing with sequences anyway. Aloha, David Sletten --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---