Reputation: 1035
I am trying to write a program that gives a list and back a newer list that have even numbers in the first list, as below:
evennom([1,3,2,4,3,2,1,2],out)
out = [2,4,2,2]
My Code is as below:
evennom([],[]).
evennom(H1|T1],[H2|T2):- H2 is H1 mod 2.
Upvotes: 1
Views: 153
Reputation: 1357
Prolog does the recursion for you..
evennom(ListIn, ListOut) :-
findall(Even, (nth0(_, ListIn, Even), 0 is (Even mod 2)), ListOut).
Upvotes: 0
Reputation: 726479
You are close - there needs to be something that removes the first element when the mod 2
operation fails. Also, your "copy" rule was not entirely correct.
Try this:
evennom([], []).
evennom([H|T1], [H|T2]) :- H rem 2 =:= 0, !, evennom(T1, T2).
evennom([_|T1], T2) :- evennom(T1, T2).
Upvotes: 1