DEV Community

Nick Bauman
Nick Bauman

Posted on

1 1

From loop recur to reduce

In Clojure, do you find yourself reaching for a loop recur but you know you should be using reduce? Here's a really simple way to break out of that habit.

Let's start with and example. Starting with a2d which is the result of invoking (to-array-2d [[11 2 4] [4 5 6] [10 8 -12]]) and len is the size of the matrix. Which is 3.

This function, written with a loop/recur, calculates the "diagonal sum" of the values of a square matrix of some size.

(defn accu [a2d len]
 (reduce +
  (loop [vals []
         i    (- len 1)]
   (if (> len (count vals))
    (recur (conj vals (aget a2d i i)) (dec i))
    vals))))
Enter fullscreen mode Exit fullscreen mode

So invoking this function:

(accu (to-array-2d [[11 2 4] [4 5 6] [10 8 -12]]) 3)
=> 4
Enter fullscreen mode Exit fullscreen mode

Returns 4 because 11 + 5 + -12 = 4

So what does the reduce version look like?

(defn accu [a2d len]
 (reduce +
  (reduce #(conj %1 (aget a2d %2 %2)) [] (reverse (range len)))))
Enter fullscreen mode Exit fullscreen mode

Notice how the relevant code is almost exactly the same. Both use (conj vals (aget a2d i i)) (dec i) to solve the problem. The loop/recur version has much more housekeeping and is not as fast as the reduce version.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay