Skip to content

Instantly share code, notes, and snippets.

@christianwish
Created August 24, 2018 14:26
Show Gist options
  • Save christianwish/d282873687097b34d1d6073c2f6ffd3a to your computer and use it in GitHub Desktop.
Save christianwish/d282873687097b34d1d6073c2f6ffd3a to your computer and use it in GitHub Desktop.
func reduceArray<A,T>(
accFunc f: (A, T) -> A
, value v: [T]
, startValue sV: A
) -> A {
if v.count == 0 {
return sV;
}
let firstValue: T = v.first!;
let newStartValue = f(sV, firstValue);
let result = reduceArray(
accFunc: f
, value: Array(v.dropFirst())
, startValue: newStartValue
);
return result;
}
let numbers = [1, 2, 3, 4]
func sumN(a: Int, b: Int) -> Int { return a + b }
let numberSum: Int = reduceArray(
accFunc: sumN
, value: numbers
, startValue: 0
);
print(numberSum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment