Last active
May 8, 2020 03:29
-
-
Save ashishkarki/5b958a67b9ca91e51eabbccc7ffbe6f9 to your computer and use it in GitHub Desktop.
Showing how fold operator works in Dart language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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