In this blog I have some posts about F# because this language seems to be interesting and is becoming popular in some companies. In this post I want to show you the reduce Function in F#.
If you have a sequence of numbers that you want to sum, F# defines the
sum operation in all of the sequential collection modules:
But what if you want to multiply all those numbers together? Well, it turns out that
sum is just a special case of a more general function that the sequential collection modules also define: reduce. The
reduce operation takes all the elements in a collection and combines them in some way to produce a single value. It uses a binary operation to combine the first two values. Then it takes the result of that first combination and combines it with the next element in the collection, and then the next, and so on through the end of the collection.
Here’s an illustration of how to use
reduce to implement a
The code looks like this:
let product = [2;5;3;6] |> Seq.reduce (fun x y -> x * y) // val product : int = 180
Another special case of
String.concat—also known as a
join operation—which allows you to concatenate a sequence of strings together with a separator in between each. Here’s how it works:
See how similar it is to the
product operation above? If you should want to implement
String.concat yourself, you could use
reduce like this:
let joined = ["do";"mi";"sol";"do"] |> Seq.reduce (fun x y -> x + "-" + y) // val joined : string = "do-mi-sol-do"
Here is the documentation on
reduce in each of the sequential collection modules:
Now a few of caveats about
- You cannot use
reduceon an empty collection. You will get an exception if you do, so make sure you check to make sure your collection is not empty before you pass it to
- The result of a
reduceoperation is always the same type as the elements in the collection. In other words, you can only reduce a collection of type
Ato a value of type
A. You cannot reduce a collection of type
Ato a value of type
- Finally, order matters if the order of your binary operation matters. In other words, with addition and multiplication, order does not matter. That is,
a + bis the same as
b + a. (Mathematicians say that such a function is commutative). But with something like subtraction, order does matter. In other words,
a − bdoes not necessarily produce the same result as
b − a. So, make sure that your binary operation applies the reduction to its operands in the correct order.
Having noted these caveats, next week, we will cover the
fold operation. It operates almost the same way as
reduce in that it walks a collection, applying a binary operation to each element. The
fold operation cannot help us with that last point—order still matters—but it can handle an empty collection and, if necessary, produce a result that is of a type different from the type of the source collection’s elements.
And this is the reduce function in F#!