Skip to content

Instantly share code, notes, and snippets.

@ashishkarki
Last active May 8, 2020 03:29
Show Gist options
  • Save ashishkarki/5b958a67b9ca91e51eabbccc7ffbe6f9 to your computer and use it in GitHub Desktop.
Save ashishkarki/5b958a67b9ca91e51eabbccc7ffbe6f9 to your computer and use it in GitHub Desktop.
Showing how fold operator works in Dart language
void sum(List<int> list){
int sum = 0;
// 1. first use a for loop to print the sum
for(int element in list) {
sum += element;
}
print('sum using for loop is: $sum');
// 2. second use fold to print sum
int foldSum = 0;
foldSum = list.fold(0, (foldSum, element) => foldSum + element);
print('sum using fold() is: $foldSum');
}
void main() {
final list = [1, 2, 3, 4, 5]; // sum is 15
sum(list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment