Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cleanest way to get the sum of numbers in a collection/list in Dart?

Tags:

iteration

dart

I don't like using an indexed array for no reason other than I think it looks ugly. Is there a clean way to sum with an anonymous function? Is it possible to do it without using any outside variables?

like image 704
Phlox Midas Avatar asked May 01 '12 22:05

Phlox Midas


People also ask

What is reduce in Dart?

reduce method Null safetyReduces a collection to a single value by iteratively combining elements of the collection using the provided function. The iterable must have at least one element. If it has only one element, that element is returned.


3 Answers

Dart iterables now have a reduce function (https://code.google.com/p/dart/issues/detail?id=1649), so you can do a sum pithily without defining your own fold function:

var sum = [1, 2, 3].reduce((a, b) => a + b); 
like image 143
ArthurDenture Avatar answered Sep 20 '22 00:09

ArthurDenture


int sum = [1, 2, 3].fold(0, (previous, current) => previous + current); 

or with shorter variable names to make it take up less room:

int sum = [1, 2, 3].fold(0, (p, c) => p + c); 
like image 36
Ugtemlhrshrwzf Avatar answered Sep 21 '22 00:09

Ugtemlhrshrwzf


This is a very old question but

In 2022 there is actually a built-in package.

Just import

import 'package:collection/collection.dart';

and call the .sum extension method on the Iterable.

FULL EXAMPLE

import 'package:collection/collection.dart';

void main() {
  final list = [1, 2, 3, 4];
  final sum = list.sum;
  print(sum); // prints 10
}

If the list is empty, .sum returns 0.

You might also be interested in list.average...

like image 26
tmaihoff Avatar answered Sep 22 '22 00:09

tmaihoff