user645785
user645785

Reputation: 29

Prolog predicate check divisibility of numbers in a list

example

divisible([L1],X) :-
L1 mod X =:= 0.

query

divisible([4,6,8,7],2).

response

[4,6,8]

Any guidance?

Upvotes: 1

Views: 6807

Answers (4)

repeat
repeat

Reputation: 18726

Use tfilter/3 in tandem with the reified test predicate divisor_of_t/3:

?- tfilter(divisor_of_t(2),[4,6,8,7],Zs).
Zs = [4, 6, 8].

Based on and bool01_truth/2, we can define divisor_of_t/3 as follows:

:- use_module(library(clpfd)).

divisor_of_t(Y,X,Truth) :- X mod Y #= 0 #<==> B, bool01_truth(B,Truth).

Upvotes: 1

Kaarel
Kaarel

Reputation: 10672

SWI-Prolog has a nice predicate include/3 which you can use like this:

?- include(divides(2), [4, 6, 8, 7], L).
L = [4, 6, 8].

given that you have defined divides/2:

% Succeeds if X divides Y
divides(X, Y) :-
    Y mod X =:= 0.

Upvotes: 2

Asterisk
Asterisk

Reputation: 3574

divisible([], _, []).
divisible([H|T], X, [H|T1]) :- H mod X =:= 0, divisible(T, X, T1).
divisible([H|T], X, T1) :- H mod X =\= 0, divisible(T, X, T1).

Upvotes: 6

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

You are going to need a three-argument predicate (input list, value to test for divisibility, and output list). After that, think about the three cases: input list is empty, first element is not divisible by number, and first element is divisible by number. You should be able to write three clauses, one for each of those, and get a correct predicate.

Upvotes: 3

Related Questions