[英]count sum of list using tail recursive function in c++
I am doing assignment for my college. 我正在为我的大学做作业。 I need to create recursive function.
我需要创建递归函数。
My list_t
interface contain following functions: 我的
list_t
接口包含以下功能:
List Interface
The file recursive.h defines the type "list_t" and the following operations on lists:
// EFFECTS: returns true if list is empty, false otherwise
bool list_isEmpty (const list_t& list);
// EFFECTS: returns an empty list.
list_t list_make ();
// EFFECTS: given the list (list) make a new list consisting of
// the new element followed by the elements of the
// original list.
list_t list_make (int elt, const list_t& list);
// REQUIRES: list is not empty
// EFFECTS: returns the first element of list
int list_first (const list_t& list);
// REQUIRES: list is not empty
// EFFECTS: returns the list containing all but the first element of list
list_t list_rest (const list_t& list);
// MODIFIES: cout
// EFFECTS: prints list to cout.
void list_print (const list_t& list);
Please note sum function need to be tail recursive and I can't use static or global variable. 请注意,求和函数必须是尾递归的,并且我不能使用静态或全局变量。
until now I have come with this which is gives me wrong answer: 到现在为止,我都给出了错误的答案:
int sum(list_t list) {
if(list.get_rest_list().is_empty())
return list.get_first_elt() + sum(list.get_rest_list());
}
Let's rewrite that function with proper indentation: 让我们用适当的缩进来重写该函数:
int sum(list_t list)
{
if(list.get_rest_list().is_empty())
return list.get_first_elt() + sum(list.get_rest_list());
// what to return here?
}
In addition to the flawed logic, you don't have all control paths covered with return
statement, which causes indeterminate value to be returned if the condition is not satisfied. 除了有缺陷的逻辑外,您还没有用
return
语句覆盖所有控制路径,如果条件不满足,这将导致返回不确定的值。
(Not so) Corrected code: (不是)已更正的代码:
int sum(list_t list)
{
if(list.get_rest_list().is_empty())
return list.get_first_elt();
return list.get_first_elt() + sum(list.get_rest_list());
}
You can rewrite this using ternary operator, if you like. 如果愿意,可以使用三元运算符重写它。
But what if you pass an empty list_t
? 但是,如果您传递一个空的
list_t
怎么list_t
? Better do this: 最好这样做:
int sum(list_t list)
{
if(list.is_empty())
return 0;
return list.get_first_elt() + sum(list.get_rest_list());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.