Java代码
package hello;
public class TestA {
public static int sum( int... numbers )
{
int total = 0;
for ( int n : numbers )
total += n;
return total;
}
public static int sum2( int... numbers )
{
return sum2Helper(0, 0, numbers);
}
private static int sum2Helper( int total, int i, int... numbers)
{
return i == numbers.length ? total :
sum2Helper(total + numbers[i], i + 1, numbers);
}
public static int sum3( int... numbers )
{
return sum3Helper(0, numbers);
}
private static int sum3Helper( int i, int... numbers)
{
return i == numbers.length ? 0 :
numbers[i] + sum3Helper(i + 1, numbers);
}
public static void main( String args[] )
{
System.out.println(sum(1, 2, 3, 4));
System.out.println(sum2(1, 2, 3, 4));
System.out.println(sum3(1, 2, 3, 4));
}
}
//运行结果
//10
//10
//10
代码说明
- sum函数使用普通的for each循环对数组求和。
sum([1, 2, 3, 4]) = 0 + 1 + 2 + 3 + 4
- sum2函数不使用循环而是用递归(左卷起)方式对数组求和。
sum2([1, 2, 3, 4]) = (((0 + 1) + 2) + 3) + 4
- sum3函数不使用循环而是用递归(右卷起)方式对数组求和。
sum3([1, 2, 3, 4]) = 1 + (2 + (3 + (4 + 0)))
Haskell代码
sum2 :: Num a => [a] -> a
sum2 l = sum2Helper l 0
where
sum2Helper [] a = a
sum2Helper (x:xs) a = sum2Helper xs (a+x)
sum3 :: Num a => [a] -> a
sum3 l = sum3Helper l 0
where
sum3Helper [] a = a
sum3Helper (x:xs) a = x + sum3Helper xs a
*Main> sum2 [1,2,3]
6
*Main> sum3 [1,2,3]
6
F#代码
let sum2 l =
let rec sum2Helper l a =
match l with
| [] -> a
| x::xs -> sum2Helper xs (a+x)
sum2Helper l 0
let rec sum3 l =
let rec sum3Helper l a =
match l with
| [] -> a
| x::xs -> x + sum3Helper xs a
sum3Helper l 0
> sum2 [1;2;3];;
val it : int = 6
> sum3 [1;2;3];;
val it : int = 6