问题是:
FunctionZ [] = 0
FunctionZ[x:xs] = x + 2 * FunctionZ(xs)
通过写入传递给每个调用的参数值来完成下表
FunctionZ
以及每次调用返回的值,当
FunctionZ [4,2,5,3]
已评估。
然后有一个表格需要填写
电话号码 | 论证 | 返回值 |
---|---|---|
1 |
|
|
2 | ||
3 | ||
4 | ||
5 |
非常感谢任何帮助。我在大学里从来没有这样做过。我理解正面和反面的概念,但仅此而已。
问题的答案如下,但我想知道如何通过逐步说明找到答案:
电话号码 | 论证 | 返回值 |
---|---|---|
1 |
|
52 |
2 |
|
24 |
3 |
|
11 |
4 |
|
8 |
5 |
|
3 |
谢谢
我尝试扩展可调用括号。
方程式
FunctionZ [] = 0
FunctionZ [x:xs] = x + 2 * FunctionZ(xs)
通过案例有效构建定义。它们相当于:(伪代码)
FunctionZ list =
if list is empty
then the result is zero
else if list starts with x (head) and continues with xs (tail)
then the result is x + 2 * FunctionZ(xs)
else runtime error: "unhandled case"
请注意,最后一个分支(“未处理的情况”)实际上从未被采用,因为您的方程涵盖了所有可能的情况:我们称之为“穷举模式匹配”。我已经包含了一般性内容。 关键方面:
FunctionZ [x:xs] = ...
这样的方程的左侧执行两个任务:它检查输入列表是否具有该形式(即非空),并同时将输入列表的头部和尾部绑定到变量
x
和xs
。这种模式匹配比使用像 head(list)
这样的函数要好得多,因为(详尽的)模式匹配永远不会崩溃,而如果 head(list)
为空,则 list
可能会崩溃。