Respuesta :
Answer:
I am writing the function in Python. Let me know if you want this function in some other programming language.
def index(elem, seq):
if len(elem) == 0:
return -1
elif elem[0] == seq:
return 0
else:
return 1 + index(elem[1:], seq)
Explanation:
The function index() takes two parameters elem which is a string array and seq that is the index to find in elem.
If the length of the elem array is 0 means the array is empty then -1 is returned.
If the 1st element at 0th index is equal to seq, which means if the index is found at the first position in the elem then 0 is returned which means that the index is found at the first (0th index) position of elem.
If both of the above condition evaluate to false then the else part is executed which calls the index() recursively. This will traverse through the elem until it finds the seq which means that it will move through elem array until it finds the desired index.
Lets see how this function works.
print(index(['banana'],'b'))
Here we call the function index() to print the index (seq) position of b in banana(elem).
So it is found in the first index which evaluates elif elem[0] == seq condition to true so output is 0.
For print (index([1,2,3,4,5,6,7,8], 3)) statement in order to find 3 seq in [1,2,3,4,5,6,7,8] elem list, the recursive function is called which calls itself recursively and keeps slicing the list to find and return the desired index.
The screenshot of program with its output is attached.