且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog - 将列表的偶数元素乘以数字(F)

更新时间:2023-02-11 16:37:36

你不应该使用剪切(! 目标).Cuts 是一个高级的 Prolog 概念,只有在您是更高级的 Prolog 程序员时才有用.在此之前,削减只会让你感到困惑.此外,削减通常不会使您的程序更频繁地成功,但它们会使它更频繁地失败.您的问题是您的程序经常失败!削减可能是您的问题的一部分.

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.

另外,你的程序总是返回 false 也不完全正确.看,它确实适用于某些输入:

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!

您现在需要做的是,在列表中的数字之一为奇数的情况下也使此操作成功.让 Prolog 程序更频繁地成功的一种主要方法是:向某个谓词添加更多子句.

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.

到目前为止,您对 evenproduct/3 的定义有两个子句.也许到目前为止您所看到的所有列表处理谓词都只有两个子句,一个用于基本情况";一个用于递归情况".但是,有几个非递归或几个递归子句是完全可以的,而且通常是非常必要的.在您的情况下,您可以将以下子句添加到您的程序中以使其工作:

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.

现在也接受奇数:

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