This is a procedure to return the last item in a list 1:
proc last (1)
if (isEmpty(1))
error('Oops. Empty list in procedure last.')
elseif (is empty(rest1))
return (first(1)
else return last(rest(1))
Modify that to create a recursive procedure getItem(i,l)
that returns item i
in a list 1, where i
is an integer greater than zero.
proc getItem(i,1)
if (isEmpty(1))
error('Opps. Empty list in procedure last.')
else if (isEmpty(getItem,i1)
else if i > 0
return item(i,1)
is that correct?
For it to work recursively, that last line needs to have the same name of the function.
Besides that, you need to decrease i .... otherwise you aren't moving...
should be something like:
proc getItem(i,1)
if (isEmpty(1))
error('Opps. Empty list in procedure last.')
else if (i > 0)
return getItem(i-1,1)
else return first(1)
What language are you using? In most languages you cannot use numbers as variable names. Also, you're missing a couple of parenthesis and you're not using 'else if' consistently.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.