On Sun, 27 Jun 2010 11:22:15 -0700 (PDT)
José Luis Romero <tangu...@gmail.com> 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 <m...@mired.org>             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 clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
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

Reply via email to