Reputation: 10784
I'm doing an exercise in Prolog using SWI-Prolog, to take a nested list and convert it into a list of elements and then make the sum of the elements, I made two separate predicates which make me both functionalities:
my_flatten(X,[X])->Transform a list, possibly holding lists as elements into a 'flat' list by replacing each list with its elements (recursively).
my_flatten(X,[X]) :- \+ is_list(X).
my_flatten([],[]).
my_flatten([X|Xs],Zs) :-
my_flatten(X,Y), my_flatten(Xs,Ys), append(Y,Ys,Zs).
addList-> Adds all the elements of a list and returns their sum
addList([],0).
addList([X|Xs],N):-
addList(Xs,N0),N is X+N0.
The problem itself is that I'm new programming in Prolog and I don't know how join both predicates in the same predicate, so that the list returned by my_flattern be used by the predicate addList. Maybe it's a bit foolish question, but I've been stuck on it for days. I need some help to clarify this question for other problems
Upvotes: 1
Views: 1243
Reputation: 10819
To construct a new predicate which does both, simply call both my_flatten
and addList
, with a shared variable:
addListFlattened(L, Sum) :-
my_flatten(L, L2),
addList(L2, Sum).
addListFlattened
is a new predicate (you can change the name), which reuses addList
.
Upvotes: 2