0
votes

For a problem in my class, I'm having trouble figuring out how to read through a list of numbers in Prolog. The idea is that a predicate called contains_big would read through a list of given numbers, and respond with "true" if a number in that list is over 100, and false if not.

contains_big([40, 692, 2, 800, 7]). = true
contains_big([2, 4, 6]).            = false

How would this be accomplished in prolog?

1

1 Answers

1
votes

From an earlier exercise we have predicate classify/2

% classify(+N, ?Classification)

classify(N, small)   :- must_be(number,N), N < 50, !.
classify(N, medium)  :- must_be(number,N), N >= 50, N =< 100, !.
classify(N, big)     :- must_be(number,N), N > 100.

Now you just have to apply that predicate to every element in the list, in effect performing a disjunction of the query classify(N,big) for every N in that list.

Here is a simple way: We code the inductive definition...

  • A nonempty list [N|_] starting with N contains a big element if N is big (and the we do not need to look at the rest of the list, and the Prolog to not try the next clause by adding a !).
  • A nonempty list [_|More] starting with anything and continuing with More (which may or may not be the empty list) contains a big element if More is a list containing a big element.
contains_big([N|_])    :- classify(N, big),!.  
contains_big([_|More]) :- contains_big(More).

And that's it, really.

And so:

?- contains_big([]).
false.

?- contains_big([1,2,3]).
false.

?- contains_big([1,200,3]).
true.

?- contains_big([200,200,200]).
true.