Home > Software engineering >  Prolog - Multiply the even elements of a list by a number (F)
Prolog - Multiply the even elements of a list by a number (F)

Time:10-25

I am programming in Prolog looking from any given number (F), to multiply the even elements of a list; keeping those values ​​that are not, developed the following and in fact the program "compiles" without any error but when entering values ​​it only returns "false", where could I be wrong ?:

% base case
evenproduct(_,[],[]) :- !.

% recursive case
evenproduct(F,[X|Xs], [Y|Ys]) :-
   Y is F*X,
   X mod 2 =:= 0,
   evenproduct(F, Xs, Ys), !.

Thanks!!

CodePudding user response:

You shouldn't use cuts (the ! goal). Cuts are an advanced Prolog concept that are only useful once you are a much more advanced Prolog programmer. Before that, cuts will only confuse you. Also, cuts will usually not make your program succeed more often, but they will make it fail more often. Your problem is that your program fails too often! Cuts might be part of your problem.

Also, it's not quite correct that your program always returns false. Look, it does work for some inputs:

?- evenproduct(3, [2, 4, 6], Ys).
Ys = [6, 12, 18].

Namely, if the given list only contains even numbers, your program works exactly as intended. Good job so far!

What you now need to do is to also make this succeed for the case where one of the numbers in the list is odd. There is one main way of making a Prolog program succeed more often: Adding more clauses to some predicate.

Your definition of evenproduct/3 has two clauses so far. Maybe all the list processing predicates you've seen so far have always had exactly two clauses, one for "the base case" and one for "the recursive case". But it's perfectly fine, and often very necessary, to have several non-recursive or several recursive clauses. In your case, you can add the following clause to your program to make it work:

evenproduct(F,[X|Xs], [Y|Ys]) :-
   Y = X,
   X mod 2 =:= 1,
   evenproduct(F, Xs, Ys).

So now you will have three clauses in total, one non-recursive and two recursive ones.

And now odd numbers are accepted as well:

?- evenproduct(3, [1, 2, 3, 7, 11, 22], Ys).
Ys = [1, 6, 3, 7, 11, 66] ;
false.
  • Related