Created
March 14, 2012 08:15
-
-
Save adam-singer/2035060 to your computer and use it in GitHub Desktop.
Sum of Squares in Dart using a fold function
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
removeOne(list) { var i = list[0]; list.removeRange(0,1); return i; } | |
fold(value, f(v, n), List ns){ | |
if (ns.isEmpty()) return value; | |
return fold(f(value, removeOne(ns)), f, ns); | |
} | |
// sum of squares becomes | |
sumOfSquares(list) => fold(0, (v, n) => v + n * n, list); | |
main() { | |
print(sumOfSquares([])); | |
print(sumOfSquares([1,2,3])); | |
print(sumOfSquares([10])); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment