[Cs254f11] Repeat a function call

Lee Spector lspector at hampshire.edu
Wed Oct 5 06:22:30 EDT 2011


Indeed, repeatedly. And note that the second argument to repeatedly has to be a function (which should take no arguments). 

It's tempting to try (repeatedly 5 (rand-int 20)) but that's not right; it would evaluate (rand-int 20), get a number from that, and repeatedly try to call that number as a function (which won't work). The #(...) anonymous function syntax generally works well in this case, as Omri did it, since the function takes no arguments so you don't have to use % for args. But you could instead use a defined/named function or an anonymous function with the (fn [] ...) syntax if you prefer:

(defn randfoo [] (rand-int 20))

(repeatedly 5 randfoo)

; (3 0 19 19 9)

(repeatedly 5 (fn [] (rand-int 20)))

; (17 19 15 17 14)

 -Lee

On Oct 4, 2011, at 11:42 PM, Omri Bernstein wrote:

> Jack-
> 
> You might be looking for the function "repeatedly". As in:
> 
> (repeatedly 5 #(rand-int 20))
> >> (12 18 16 11 19)
> 
> -Omri
> 
> 
> On Tue, Oct 4, 2011 at 11:13 PM, Jack Laxson <jrl11 at hampshire.edu> wrote:
> Lee: what was the repeated function call you told us to use earlier today? I've managed to hit that same problem.
> 
> (def initial (repeat 5 (rand-int 20))). Which repeats the random int that it gets. I checked the cheatsheet (http://clojure.org/cheatsheet) for the others but I think there was a way better way to form it.
> 
> _______________________________________________
> Cs254f11 mailing list
> Cs254f11 at lists.hampshire.edu
> https://lists.hampshire.edu/mailman/listinfo/cs254f11
> 
> 
> _______________________________________________
> 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