Oh well.. Thanks for the tips!!! On Mon, Jun 28, 2010 at 1:37 PM, Mike Meyer <[email protected]> wrote:
> On Sun, 27 Jun 2010 11:22:15 -0700 (PDT) > José Luis Romero <[email protected]> wrote: > > > Hi! I am learning the core of clojure, and so far, I am loving it. But > > I am not a lisp programmer (python, java, among others), but never > > functional programming. I am practicing with codingbat.com, coding the > > exercises on clojure. I am stuck with loops. I want to concatenate n > > times a string. For example, given the parameters 3 and "code" the > > output will be "codecodecode". How can I do a loop in order to get > > this output. > > > > I know that this is a very newb question, any help will be > > appreciated. > > You really shouldn't be doing loops in clojure. There's almost always > a non-looping construct that solves the same problem. I.e., your > string repeat would be: > > (apply str (repeat 3 "code")) > > Other than that, there are two "common" looping constructs: > dotimes and recur. You can find out about them by asking at the repl: > > user> (doc dotimes). > > Except loop points you to the web, so here's a summary: > > recur terminates a loop that was started by either a "loop" or > "defn". recur has the form (recur new-values). An initial loop > statement has the form (loop [var value ...] body). Defn you should > know :-). The recur statement goes back to loop replacing the value of > each var (either in the loop or function arguments) with the new > values in the recur statement. > > You could write your string-repeater as: > > (defn string-dup [count string-in] > (loop [count count resuls string-in] > (if (== count 0) > result > (recur (dec count) (str result string-in))))) > > But again, the better way would be > > (defn string-dup [count string] > (apply str (repeat count string))) > > <mike > -- > Mike Meyer <[email protected]> > http://www.mired.org/consulting.html > Independent Network/Unix/Perforce consultant, email for more information. > > O< ascii ribbon campaign - stop html mail - www.asciiribbon.org > -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to [email protected] Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/clojure?hl=en
