Prolog predicate check divisibility of numbers in a list
example
divisible([L1],X) :-
L1 mod X =:= 0.
query
开发者_StackOverflowdivisible([4,6,8,7],2).
response
[4,6,8]
Any guidance?
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).
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.
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.
Use meta-predicate 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 clpfd 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).
精彩评论