Exercise 1.12
Write a procedure that computes elements of Pascal's triangle by means of a recursive
process.
-
def elem(n, m) {
-
if (m == 1 || m == n) return 1
-
else if (m < 1 || m > n) return 0
-
else return elem(n-1, m-1) + elem(n-1, m);
-
}
-
-
def line(n) {
-
def line_iter;
-
line_iter = { total, id ->
-
if (id > total) return [];
-
else return ([elem(total, id)] + line_iter(total, id+1));
-
}
-
return line_iter(n, 1);
-
}
-
-
def pascalTriangle(n) {
-
def impl = { id ->
-
if (id == 0) return "";
-
else return "${pascalTriangle(id - 1)}\n${line(id)}"
-
}
-
return impl(n);
-
}
-
-
println pascalTriangle(7);
------------------result----------------
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
上面那一版pascalTriangle()写得不好,定义了一个多余的闭包。下面是修改版:
-
def elem(n, m) {
-
if (m == 1 || m == n) return 1
-
else if (m < 1 || m > n) return 0
-
else return elem(n-1, m-1) + elem(n-1, m);
-
}
-
-
def line(n) {
-
def line_iter;
-
line_iter = { total, id ->
-
if (id > total) return [];
-
else return ([elem(total, id)] + line_iter(total, id+1));
-
}
-
return line_iter(n, 1);
-
}
-
-
def pascalTriangle(n) {
-
if (n == 0) return "";
-
else return "${pascalTriangle(n - 1)}\n${line(n)}"
-
}
-
-
println pascalTriangle(7);
阅读(442) | 评论(0) | 转发(0) |