user721588
user721588

Reputation:

dealing with lists in Prolog (removing elements)

How can I delete all elements from a list which can be divided by 3 (i.e. x % 3 == 0)?

Upvotes: 1

Views: 302

Answers (3)

Junuxx
Junuxx

Reputation: 14251

Here's a predicate removemod(+List,+Mod,?Result):

removemod([],_,[]).
removemod([H|T],M,[H|T2]):-
    H mod M =\= 0,
    removemod(T,M,T2).
removemod([H|T],M,T2):-
    H mod M =:= 0,
    removemod(T,M,T2).

Seems to work:

15 ?- removemod([3,7,5,12,8,2,16,13,9,11,27],3,L).
L = [7, 5, 8, 2, 16, 13, 11] .

16 ?- removemod([66933],3,L).
L = [].

Upvotes: 2

m09
m09

Reputation: 7493

The idiomatic way of doing this is to use higher order, in SWI for example, there is a nice predicate called exclude/3 that does exactly what you want (remove elements based on a predicate):

clean(List, FilteredList) :-
    exclude(mod3, List, FilteredList).

mod3(X) :-
    X mod 3 =:= 0.

And higher order is way classier with the lambda library:

:- use_module(lambda).

filterMod3(List, FilteredList) :-
    exclude(\X^(X mod 3 =:= 0), List, FilteredList).

Upvotes: 2

whd
whd

Reputation: 1861

or much simpler findall(X,(member(X,[1,2,3,4,5,6,7,8,9,10]),0 =:= X mod 3),Y).

Upvotes: 0

Related Questions