0
votes

I recently wanted to experiment with Prolog to understand how the process of unification works so I wrote the following code to return the nth element from a list.

getfromarray([X|_],1,X).
getfromarray(A,N,E):-
    N > 1,
    A = [_|Y],
    N1 is N-1,
    getfromarray(Y,N1,E).

However, upon entering the input to the program as
getfromarray(A,3,E), it returns :-

A = [_G5129, _G5132, E|_G5136]

I understand that since i wrote the rule A = [_|Y] , A is being unified to satisfy the conditions of the rules in the program hence A is being displayed in this format. However, I don't understand why E is not being unified with the value in the array. I did read through the basics of unification in Prolog and I understand that while the answer is not wrong, it does not do what it is intended to do. Can someone suggest a topic in unification I might have missed upon which might help me solve this minor issue?

EDIT: When I passed a list as a parameter to the program, it gave the associated value of E in the list.However, when I unified a variable A with a list and passed A as a parameter to the program, It is displaying the same output as i mentioned above.

5 ?- getfromarray([1,2,5,4,5],3,E).

E = 5 .

6 ?- A = [1,2,3,4,5].

A = [1, 2, 3, 4, 5].

7 ?- getfromarray(A,3,E).

A = [_G576, _G579, E|_G583] .

8 ?-

1
E is unified with the 'value' in the array: a shared, uninstantiated variable, created recursing down to 1...CapelliC
Hello, Thanks for the feedback!!! I tried passing a list as the parameter to the program and it gave the associated value of E to the element in the list. However, when i unified a Variable A to a list and then passed A as a parameter to the program, it gave the same output as above.Vegesana Praneeth

1 Answers

0
votes

Prolog doesn't store your list A, therefore A is uninstantiate.

A = [1, 2, 3, 4, 5].
getfromarray(A,3,E). 

This is like just calling :

getfromarray(A,3,E). 

Try this in stead :

A = [1, 2, 3, 4, 5], getfromarray(A,3,E).