Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

logic - Excluding even numbers in Prolog

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...