bp99
bp99

Reputation: 348

More complicated goals in higher order Prolog

Let me give a concrete example to explain my question:

Given a list of lists LoL and a list Ex, construct X that contains all elements (sublists) of LoL after subtracting Ex from them.

Just to give you an example:

?- my_exclude([[1, 2, 3], [1], [3, 4]], [2, 3], X).
X = [[1], [1], [4]].

I know that I could use subtract/3 from the lists library, but I can’t figure out how to implement this kind of mapping.

I know maplist, but I don’t see how I could make use of that here.

What I am probably missing is some kind of map predicate that would transform LoL into X while applyling an operation to each element, that operation being the subtraction of Ex.

How could I go about doing this, without resorting to ‘manually’ implementing this on a lower level, recursively?

(In other words, maybe I am looking for lambdas, that don’t seem to exist in standard Prolog)

Upvotes: 1

Views: 85

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

You need to call subtract(Li, [2,3], Ri) for each Li in the list L to produce a result Ri in the result list R.

You can make use of a lambda expression with:

my_exclude(L, E, R) :-
    maplist({E}/[Li, Ri]>>subtract(Li, E, Ri), L, R).

Here {E}/[Li, Ri]>>subtract(Li, E, Ri) is thus a goal with two variables Li and Ri that will, when called, call subtract(Li, E, Ri) where E is the list of elements we want to exclude.

Upvotes: 2

Related Questions