Reputation: 267
If I have a pre-initialized list, for example:
List = [_1663, _1665, _1667]
How can I put a variable (like a simple integer) in this list, taking up the first free spot?
I tried:
append(5, List).
But that doesn't work. The list must be pre-initialized like above. Any ideas? Thank you.
Upvotes: 0
Views: 130
Reputation: 58244
Prolog will not automatically instantiate the next free variable in a list. You can easily, though, do this with a predicate:
bind_first_free_element(Element, List) :-
once(bind_free_element(Element, List)).
bind_free_element(X, [Y|_]) :-
var(Y), X = Y.
bind_free_element(X, [_|T]) :-
bind_free_element(X, T).
When you query, you get:
2 ?- L = [a,X,Y,b,Z], bind_free_element(5, L).
L = [a, 5, Y, b, Z],
X = 5 ;
L = [a, X, 5, b, Z],
Y = 5 ;
L = [a, X, Y, b, 5],
Z = 5 ;
false.
So you can see that bind_free_element
shows all of the possible solutions for binding a free element. Thus, we use bind_first_free_element/2
that uses once/1
to only seek the first solution:
3 ?- L = [a,X,Y,b,Z], bind_first_free_element(5, L).
L = [a, 5, Y, b, Z],
X = 5.
Upvotes: 2