[Cs254f11] Recursion without loop
Lee Spector
lspector at hampshire.edu
Wed Nov 2 20:30:16 EDT 2011
First, just a little note that the first argument to "some" can be a set, in which case it is interpreted as a function that looks up the set elements in the second argument, so your call to (some #(= [x y] %) checked) could instead be slightly simpler as (some #{[x y]} checked).
That said, I'd approach your lib-test function in a slightly different way (but I do pass a set to "some", so I wanted to explain that above). The following is untested code (I can't easily test it without the rest of your code), but it shows the general approach I might take to this:
(defn lib-test
[x y]
(loop [unchecked (friends x y)
checked [[x y]]]
(if (empty? unchecked)
checked
(if (some #{(first unchecked)} checked) ;; already dealt with the first guy
(recur (rest unchecked) checked)
(recur (concat (friends (first (first unchecked)) (second (first unchecked)))
(rest unchecked))
(conj checked (first unchecked)))))))
-Lee
On Nov 2, 2011, at 6:51 PM, Maxwell William Fair Levit wrote:
> Hey all, I'm rewriting the function that will determine the structure of a group
> of stones and I'm a bit stuped.
>
> Here is the function that finds the pieces next to a given piece that share a
> color (rewritten very prettily by Lee)
>
> (defn friends
> [x y]
> (let [c (get @board [x y])]
> (filter #(= (get @board %) c)
> [[(+ x 1) y]
> [(- x 1) y]
> [x (- y 1)]
> [x (+ y 1)]])))
>
>
> What I want to do is take that function and call it on a given space, then call
> it again on all the spaces it returns that haven't already been counted, and so
> on until all pieces in the group have been counted.
>
> What I have looks like this:
>
>
> (defn lib-test
> [x y checked]
> (if (not (some #(= [x y] %) checked))
> (apply lib-test (friends x y) (conj checked [x y]))
> checked))
>
> What I can't do is figure out how to apply (or map) lib-test to a bunch of
> vectors, while having the extra argument 'checked' tacked on the end, but not
> coming from the vectors.
>
> Does this make sense? Can someone tell me how to make this work?
>
> Thanks,
>
> -Max
> _______________________________________________
> Cs254f11 mailing list
> Cs254f11 at lists.hampshire.edu
> https://lists.hampshire.edu/mailman/listinfo/cs254f11
--
Lee Spector, Professor of Computer Science
Cognitive Science, Hampshire College
893 West Street, Amherst, MA 01002-3359
lspector at hampshire.edu, http://hampshire.edu/lspector/
Phone: 413-559-5352, Fax: 413-559-5438
More information about the Cs254f11
mailing list