Question

In Scala's Collections library - we see the Seq Class which has the reduceOption method:

def reduceOption[A1 >: A](op: (A1, A1) ⇒ A1): Option[A1]

Reduces the elements of this sequence, if any, using the specified associative binary operator."

This has another great explanation here:

Here comes reduceOption to save the day! If the reduce would fail because the collection was empty, it will just return a None instead, and a Some(returnvalue) for nonempty collections.

My question is: What is the Clojure equivalent of Scala's seq.reduceOption?

Was it helpful?

Solution

It's simply called reduce:

user> (reduce + (range 1e6))
499999500000  

user> (reduce + [])
0

In the second case the result of zero comes form the fact that the identity value for addition is zero, so if you call the + function with no arguments it will return 0. for * the return value would be one. This requires that the function you pass be able to handle being called with zero, one, or two arguments. You can prevent this behavior by specifying the initial value as a third argument, in which case your reducing function is never called if the list is empty.

user> (reduce * -1 [])
-1 

Reduce also uses the forkjoin framework when called on collections that support this such as vectors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top