On Fri, 22 Oct 2010 03:48:44 -0700 (PDT)
Marc von Bihl <[email protected]> wrote:
> Hello, I am new to fucntional programming and have 2 questions:
>
> How can I apply a function to each element from a list and a second
> parameter?
>
> (def lstr '("Hello1" "Hello2" "Hello3"))
>
> (defn addtoString [s1 s2]
> (str s1 s2))
>
> (apply (addtoString lstr "World"))
The canonical way would be with an anonymous function:
(map #(addtoString % "World") lstr)
FWIW, standard usage is a vector rather than a quoted list for
sequences of constants:
(def lstr ["Hello1" "Hello2" "Hello3"])
> ---------
>
> I need it for the following example (pseudo code).
> How would you realize this in Clojure?:
>
> function testit [times, function, list, s]
> for (0 to times)
> def start = System.nanoTime()
> def results = []
> for (i = 0 to list.length())
> results.add(function(listelement(i), s))
> def end = System.nanoTime()
> println "run took " end-start " ns"
> println "results are: "
> results.each { result => println result }
This kind of timing on the JVM isn't really very reliable (hotspot JIT
compilation w/ optimizations and similar things tend to make the
results do screwy things), but most of this is a fairly
straightforward translation (assuming "listelement(i) is actually
something like "list.element(i)" - the ith element in list):
(defn testit [times function list s]
(dotimes [_ times]
(let [start (. System nanoTime)
result (for [item list] (function item s))
end (. System nanoTime)]
(println "run took" (- end start) "ns")
(println "results are:")
(map println results))))
--
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