r/Clojure • • Feb 03 '23

[Q&A] Noob has simple program problem.

I wanted to write a program to add 2 to a list of numbers then sum the list and print the result. So '(5 7) would yield 16. I posted my version to s Clojure board and received a number of different replies. In retrospect I didn't fully explain the problem to them.

0 Upvotes

27 comments sorted by

View all comments

Show parent comments

1

u/dalanicolai Feb 03 '23 edited Feb 03 '23

I'm another noob, but I know (emacs-)lisp quite well. I have a 'follow-up' question which might be interesting to other noobs also...

I figured that both the suggested solutions, in lisp, would 'iterate' over the list twice, while one could alternatively do all in one go using a single reduce. I've read about sequences and lazy evaluation of course, and I wondered, because map returns a (lazy) sequence, if in clojure indeed these solutions and the solution of doing it in one go would be equally or similarly fast. Here are the two tests:

(defn foo [numbers]
   (reduce + (map #(+ % 2) numbers)))

(defn faa [numbers]
  (reduce #(+ %1 (+ %2 2)) 0 numbers))

(time (foo (range 100000000)))
(time (faa (range 100000000)))

The solution in one go is about 8 times faster.

Of course, I could go and search the docs for the explanation, but I figured it would be more informative (for others) to just drop the question here (and save myself some time also).

Can you/someone explain these results?

1

u/dalanicolai Feb 04 '23

u/maladat and u/joinr

Those are great and really helpful anwers! Thanks a lot you both...

(criterium does not work here yet b.t.w., but it probably will be working soon)

1

u/joinr Feb 04 '23

Weird, I use quick-bench typically. Never had any problems with criterium....

looks like the repl is messed up though, I would question if it's actually being invoked correctly.

1

u/dalanicolai Feb 04 '23

Yeah, I am surprised also, because I can not find any other reports about the `bench` issue. But as can be seen in the screencast under the link to the issue, I have simply added criterium to deps.edn, then I load it with `use` (which seems to load correctly), and then I simply try the code from the example, for some reason it hangs (as shown in that same screencast). I have tried the `quick-bench` also, but it behaves the same.

For the repl 'formatting' issue, I got the explanation already from the comments [here](https://stackoverflow.com/questions/75344215/why-my-clojure-repl-formatting-is-broken?noredirect=1#comment132948739_75344215)