Reputation: 95
Let L be a numerical list and consider the following Prolog definition for a predicate g(list,list) with the flow model (input,output):
g([],[]).
g([H|T],[H|S]):-
g(T,S).
g([H|T],S):-
H mod 2 =:= 0,
g(T,S).
Give the result of the following goal: g([1,2,3],L). Justify the answer.
I have seen that the result will be [1,2,3] when it goes only on the second branch and the second anwer is [1,3] when it combines with the third branch which excluded even numbers. Is this a good explanation?
Upvotes: 1
Views: 93
Reputation: 878
The idea is to run the predicates to form a list with no even numbers.
Explanation:
Let's start with an example [1,2,3], the predicate takes the first H (1) and checks the condition (\+(0 is H mod 2))
, so 1 mod 2 is not zero, hence condition is true and this 1 is pushed into the List. Now moving on the next H (2), checking condition, the condition fails because 2 mod 2 is 0, now checking the next predicate for 2, here the condition (0 is H mod 2)
satisfies but we will NOT push it into the list. Next comes H (3), satisfies the condition (\+(0 is H mod 2))
and is pushed into the list. Then H ([]) so first predicate succeeds and program stops.
exclude_even([],[]).
exclude_even([H|T],[H|List]):-
\+(0 is H mod 2),!,
exclude_even(T,List).
exclude_even([H|T],List):-
0 is H mod 2,!,
exclude_even(T,List).
?- exclude_even([0,1,2,3,4,5],L).
L = [1, 3, 5]
?- exclude_even([1,2,3],L).
L = [1, 3]
Upvotes: 2