问题
Write predicate evenNumbers(L1, L2)
which is true if the list L1
containing random integers and the list L2
contains even integers from L1
.
For example:
?-evenNumbers ([2,1,-3,6,8,9], L2).
»Your program returns L2 = [2,6,8].
My code is:
evenNumbers([],[]).
evenNumbers([H|T],L):-
integer(H),
0 is H mod 2,
append([H],L,L);
evenNumbers(T,L).
回答1:
Your code has multiple issues append([H],L,L);
will stop recursion and give you a wrong list also your if-then-else statement isn't right .So you could write:
evenNumbers([],[]).
evenNumbers([H|T],L1):-
integer(H),
(H mod 2 =:=0 -> L1=[H|T1],evenNumbers(T,T1);
evenNumbers(T,L1) ).
Example:
?- evenNumbers([2,1,-3,6,8,9], L2).
L2 = [2, 6, 8].
Another way writing it would be:
evenNumbers(L1,L2):-findall(X,(member(X,L1), X mod 2=:=0),L2).
来源:https://stackoverflow.com/questions/40566662/prolog-find-even-numbers-add-them-on-a-list