Cartesian product of a list in Prolog

Viewed 219

So what I want to achieve is the following: A predicate that when given 2 lists returns a list of the Cartesian products of the elements. Here is an example.

list_mult([1,2,1],[3,4],X).
X = [3,4,6,8,3,4]

So far is have this predicate that when given 2 lists of numbers will return the Cartesian product of both lists in a list of lists:

product(X,Y,Z):-
    findall([A,B], (member(A,X), member(B,Y), Z).

example: product([1,2],[3,4],X).
X = [[1,3],[1,4],[2,3],[2,4]]

So now that i have a list of lists with all the products that i need to do I want to write another predicate that will multiply the elements of a same sub-list between each other:

sublistprod([[H|T]|T1],Lfinal):-
    mul(H,T,R),
    L = [],
    add_list(L,Res,Lfinal),
    %sublistprod(.., ..).

where "mul" and "add_list" are defined as:

mul(A,B,C):-
    C is A * B.

add_list(L,E,R):-
    append(L,[E],R).`

What I'm not sure of is how to call the "sublistprod" predicate recursively, by that I mean what do I put in the parameters of the predicate. I have tried calling sublistprod(T1,Lfinal) and that doesn't seem to work.

Any help will be most appreciated.

0 Answers
Related