I’ve just starting working with Prolog and I don’t understand how to work with multiple predicates.
For example I have to solve the following problem: Substitute in a list a value with all the elements of another list.
This is the code that I managed to write so far:
domains
elem=integer
list=elem*
predicates
%append to a list already created another list. There are 3 list parameters
%because I don't know other method
append (list,list,list)
%This will search the list (the first one) for the searched element and
%it is it will replace it with the list(the second one). The result will be
%kept in the third list.
add(list,list,elem,list)
goal
add([1,2,3,2,1],[4,5],2,L),
write (L).
clauses
add ([],[_],_,[]).
add ([A|L],L1,E,[A|L2]):-
add(L,L1,E,L2).
add ([E|L],L1,E,L2):-
add(L,L1,E,L2).
append([],[],L2).
append([],[X|L1],[X|L2]):-
append([],L1,L2).
Does your
appenddefinition is working? I think should beThe
appendpredicate it’s one of the most basic tools in Prolog programming, better to keep the usual behaviour, or to change name…Instead of
add, a better name could bereplace_elem_with_list.To implement it you should iterate, inspecting each element, and when you find a match to what’s required to replace append the list instead of copying the element.
Something like
I’ll leave you the other 2 cases that you will need to cover (when element doesn’t match and recursion base, which are similar to append)
the result: