Clojure-snips: Using reduce with sequences in Clojure


Reduce is a very common thing in functional programming. In this post we will look at simple examples using reduce in Clojure

A simple example would be to use it to sum all elements in a sequence.

(reduce + [1 2 3])

By itself it is very simple but we can combine with other things. Like we can use it with map to find the length of a sequence

(reduce + (map (fn[x] 1) [1 2 3]))

Initially we use map to get a 1 for each element in the sequence and then we reduce it.

To sum all odd or even numbers in a list we can combine it with filtering

(reduce + (filter odd? [1 2 3]))
(reduce + (filter even? [1 2 3]))

So basically it is converting multiple values into one using some function. It applies the function supplied to first two elements in the sequence and uses their result with the third element and so forth.

But we can also supply a default value

(reduce + -2 [1 2 3])

Here -2 is a random default value that I chose. You can use any default. This will be used along with the first value.

Is the above not making sense about how it works? Try this in your REPL

(reduce println -2 [1 2 3])

This will print the sequence in which println is used. Hope this helps. You can check the docs for reduce but I found the explanation a bit less formatted so you can alternately read the PR that I submitted.

Advertisements

One thought on “Clojure-snips: Using reduce with sequences in Clojure

  1. Pingback: Writing about Clojure | ansh bansal

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s