I am thinking how to multiply all elements of two list with each other. Then I want to put all results in List3
. For example,
List1 = [1,3,5].
List2 = [2,6,7].
List3
should contain [1x2, 1x6, 1x7, 3x2, 3x6, 3x7, 5x2, 5x6, 5x7].
In the end;
List3 = [2, 6, 7, 6, 18, 21, 10, 30, 35].
Is it possible to do that? How to do that? I couldn't find a right way.
Here is a rather straight-forward solution using
library(lambda)
So we have an outer-loop for
Xs
and an inner loop forYs
.Replace
(YP=X*Y)
by(YP is X*Y)
or(YP #= X*Y)
. Whatever you prefer.Well,First take a look on this question executing operation for each list element in swi-prolog and others to know how to do
for-each
operation onlists
.Second, here is the code:
output:
A simple solution not requiring any Prolog extensions (but, of course, loosing the potential benefits of using CLP(FD)) would be:
This solution is tail-recursive and doesn't leave spurious choice-points.
Use dcg! "Cross product"—shown here—is just one of many applications. Proceed like this:
Let's use clpfd and lambdas to run the query you provided in your question:
Above lambdas use difference-lists explicitly; with
phrase//1
we can also use them implicitly!clpfd enables us to do very general queries. Thanks to @PauloMoura for his suggestion! Look!
Why not