1

example

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

query

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

response

[4,6,8]

Any guidance?

user645785
  • 29
  • 1
  • 4

4 Answers4

6
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).
Asterisk
  • 3,534
  • 2
  • 34
  • 53
3

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.

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
  • thanks. but what about the other elements in the input list? You only mention the first element – user645785 Mar 05 '11 at 06:38
  • @user645785: Those are handled in recursive calls in the last two of the cases I mentioned. – Jeremiah Willcock Mar 05 '11 at 06:41
  • I am new to prolog, how can you cycle through the values in a list? Any pseudo code? – user645785 Mar 05 '11 at 06:42
  • Here's the second case: if the list is of the form `[H|T]` and `H` does not divide `D` (the second argument), you return the result of calling your same predicate on `T` and `D`. The third one is similar except that you prepend `H` to the result. – Jeremiah Willcock Mar 05 '11 at 06:44
  • Like: divisible([H|T],Y) :- T mod Y =:= 0. But that doesn't work because T is a list itself – user645785 Mar 05 '11 at 06:49
2

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.
Kaarel
  • 10,554
  • 4
  • 56
  • 78
1

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).
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166