Dan
Dan

Reputation: 1183

(Prolog) Get numbers within a range from a list

I'm trying to get all numbers between 10 and 40 (inclusive) from a list, and outputting to another list. So far my code sort of works but does not yield the desired result. The catch is that I can't use system predicates.

rangeTenForty([], List2).
rangeTenForty([H|T], List2) :- H >= 10, T =< 40, rangeTenForty(T, List2).
rangeTenForty([H|T], List2) :- rangeTenForty(T, List2).

A few conditions:

?- rangeTenForty([400, 13, 20, 50], X). returns the answer X = [13, 20], a query

?- rangeTenForty([100, 5, 77], X). returns the answer X = [], but a query

?- rangeTenForty([12,25,2004], [12,2004]). must return the answer no.

Any help is really really really appreciated. Thanks very much.

Upvotes: 1

Views: 1510

Answers (1)

turingcomplete
turingcomplete

Reputation: 2188

You need to correct a few things.

rangeTenForty([], []).
rangeTenForty([H|T], [H|L]):- H >= 10, H =< 40, rangeTenForty(T, L).
rangeTenForty([H|T], L):- (H < 10;H > 40), rangeTenForty(T, L).

Upvotes: 2

Related Questions