DEV Community

oganao
oganao

Posted on

Applying reduce to a list with no element. Oops.

I have the following code. Getting datetimes from a list of a model, removing a datetime if the date is today, and gaining the max value, is simple functional programming. It works fine, but sometimes 'No element' exception occurs.


var maxDate = list
//removing today's data.
.where((e) => !Util.isSameDay(e.datetime, DateTime.now()))
.map((e) => e.datetime)
// getting the max value.
.reduce((v, e) => v.isAfter(e) ? v : e);

At first, I didn't figure out what the problem is. I spent some time trying to solve it.

The reason is simple. The reduce document says

The iterable must have at least one element

So, following the above code, we sometimes have a list with no element before we apply the reduce function.

I know how to use the reduce function, but I completely forgot the specification when I coded.

I use Android Studio, which is really awesome, but I hope the code inspector warns of such the code.

Top comments (3)

Collapse
 
prsaya profile image
Prasad Saya

The list's fold method allows working with empty collection.

Collapse
 
oganao profile image
oganao

Yes, I should have know that. Anyway, In my case, I need to get the max value, so I have to check if the list is empty before I apply fold or reduce.

Collapse
 
prsaya profile image
Prasad Saya

You can use different approaches to the issue. As you mentioned, you can check for the empty list before applying the reduce (and add a max value to the list if it is empty), use just use the fold (and avoid the additional check), or some other approach. In general functional programming (reduce, map, filter/where, fold, etc., are functional programming constructs) allows lot of flexibility. For example, reduce also can be used in place of filter and/or map. A peek at functional programming language like Haskell reveals a lot about these features and more.