Prolog: Find even numbers add them on a list

陌路散爱 提交于 2021-02-08 11:59:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!