188k views
1 vote
Define a predicate classify/3 that takes a list of integers as a parameter and generates two lists: the first containing the even numbers from the original list, and the second sublist containing the odd numbers from the original list. Your predicate should have the signature classify(List, Even, Odd).

Examples:
classify([8,7,6,5,4,3], Even, Odd).
Even = [8,6,4]
Odd = [7,5,3]

?- classify([7,2,3,5,8], Even, Odd).
Even = [2,8]
Odd = [7,3,5]

?- classify([-4,11,-7,9,0], Even, Odd).
Even = [-4,0]
Odd = [11,-7,9]

?- classify([5,13,29], Even, Odd).
Even = []
Odd = [5,13,29]

?- classify([], Even, Odd).
Even = []
Odd = []

User Henrik K
by
8.0k points

1 Answer

3 votes

Final answer:

The classify/3 predicate in Prolog separates a list of integers into even and odd numbers by recursively checking each element's divisibility by 2, using a base case for an empty list and the cut operator to prevent backtracking.

Step-by-step explanation:

The classify/3 predicate in Prolog can be defined to separate a list into two lists of even and odd integers. This can be achieved by recursively checking each element of the provided list and classifying it into the even or odd list. A base case is used for when the input list is empty.

A possible implementation of the classify/3 predicate is:

classify([], [], []).
classify([H|T], [H|Even], Odd) :-
0 is H mod 2, !,
classify(T, Even, Odd).
classify([H|T], Even, [H|Odd]) :-
classify(T, Even, Odd).

This code has a base case for an empty list, and two recursive cases: one for even numbers (where it uses the mod operator to check divisibility by 2) and one for odd numbers. The cut operator (!) is used to prevent backtracking once a number has been classified as even.

User Drew Schmaltz
by
8.6k points