'How to access an element in a list in Proplog?
In prolog, how do I access an element in a list with an index? For example, I'm writing a rule get_i(List, I, X) where List is the list I'm passing in, I is the index, and X is the element that will be returned. A sample run could be like: getget_i([a,b,c,d], 3, X).
The output will be c
Thanks
Solution 1:[1]
Assuming the point of the exercise is to figure out how to find the nth element of a list...
The easy way is something like this, where the zeroth element of the list is the head of the list, and you just recursively discard the head of the list and decrement N until N reaches 0.
nth( [H|_] , 0 , H ) .
nth( [_|T] , N , H ) :- N > 0, N1 is N-1, nth(T,N1,H).
But that doesn't allow you to invoke it in different ways:
nth([a,b,c,d,e],N,d).fails.nth([a,b,c,d,e],N,X).fails.
Doing things correctly, though, is hardly more complicated:
nth( L , N , H ) :- nth(L,0,N,H) .
nth( [H|_] , N , N , H ) .
nth( [_|T] , M , N , H ) :- var(N) , M1 is M+1 , nth(T,M1,N,H) .
nth( [_|T] , M , N , H ) :- integer(N) , M < N , M1 is M+1 , nth(T,M1,N,H) .
Now nth([a,b,c,d,e],N,X) will repeatedly succeed on backtracking yielding
N = 0, X = a
N = 1, X = b
N = 2, X = c
N = 3, X = d
N = 4, X = E
and nth([a,b,c,d,e],N,d) yields
N = 3
Solution 2:[2]
You start with apropos(element) and apropos(index) and skim for interesting and relevant predicates:
Then you ask for help(element/3) to see help for the first one and get:
nth element is good but ehh, finite domain variables sounds complicated and it's part of some weird library. Back to the first view and there's inserting elements into a set, deleting from an ordered set, end a HTML thing, nah, nah, FD set something, hook something, ANSI something, nah, domains, html, nah...
nth0/4 select/insert element at index.
Get help on that with help(nth0/4) and see:
"True when Elem is the N’th (0-based) element of List". That's relevant, and examples which show I being related to the items in a list by their position. And part of the "lists" library. Useful.
Since I already knew I was looking for nth0 or nth1 this is totally contrived, but apropos is enormously helpful and this makes for a more interesting answer than "Google it".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | TessellatingHeckler |



