Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: replace an element in a list at a specified index

Tags:

People also ask

How do I update a list in Prolog?

You can express the above in Prolog like so: update([],[],[]). update([[X,_]|Xs],[Y|Ys],[[X,Y]|XYs]) :- update(Xs,Ys,XYs).

What is Maplist in Prolog?

maplist/2 and maplist/3 are higher-order predicates, which allow the definition of a predicate to be lifted about a single element to lists of such elements. These predicates can be defined using call/2 and call/3 as building blocks and ship with many Prolog systems.

How do you get the second element in a list in Prolog?

You can move unification into the head of the clause and simply write: second([_, Second| _], Second). The notation for lists is to write the initial elements separated by commas and then a vertical bar to separate the list tail, i.e. the list containing the rest of the elements.

How do you get the head and tail of a list in Prolog?

In Prolog list elements are enclosed by brackets and separated by commas. Another way to represent a list is to use the head/tail notation [H|T]. Here the head of the list, H, is separated from the tail of the list, T, by a vertical bar. The tail of a list is the original list with its first element removed.


I'd like to have a Prolog predicate that can replace an element in a list at a specified index.

Example:

% replace(+List,+Index,+Value,-NewList).
?- L=[a,b,c,d], replace(L,1,z,L2).
L2 = [a,z,c,d]

I don't know how to do this. Thanks for your help! Loïc.