1

我有一个 Prolog 程序,该程序旨在查找列表中可被三或五整除的所有数字的平方和。但是它返回多个结果,我不知道为什么。

% --divisibility tests--

div_test(N):-
    % divisible by three?
    0 is N mod 3.
div_test(N):-
    % divisible by five?
    0 is N mod 5.

% sum of an empty list is zero (base case)
square_sum([], Sum):-
    Sum is 0.

% --recursive cases
square_sum([Head | Tail], Sum) :-
    div_test(Head),
    square_sum(Tail, TempSum),
    Sum is Head*Head + TempSum.

square_sum([Head | Tail], Sum) :-
    square_sum(Tail, TempSum),
    Sum is TempSum.

给定以下输入:

?-square_sum([1,2,3,4,5],Sum).

我得到以下输出:

Sum = 34 ;
Sum = 9 ;
Sum = 25 ;
Sum = 0.

34 是我应该得到的唯一输出

4

1 回答 1

2
% --recursive cases
square_sum([Head | Tail], Sum) :-
    div_test(Head),
    square_sum(Tail, TempSum),
    Sum is Head*Head + TempSum.

square_sum([Head | Tail], Sum) :-
    square_sum(Tail, TempSum),
    Sum is TempSum.

在第二条规则中,您不测试 div_test 是否成功。您可以在第一条规则中的 div_test(Head) 之后添加剪切(!) 或在第二条规则中添加\+div_test(Head)

您使用 SWI-Prolog,因此您可以使用在http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl找到的模块 lambda.pl 并编写

:- use_module(library(lambda)).
div_test(N):-
    % divisible by three?
    0 is N mod 3.
div_test(N):-
    % divisible by five?
    0 is N mod 5.

square_sum(Lst, Sum) :-
    foldl(\X^Y^Z^((div_test(X); div_test(X))
              ->  Z is Y + X*X
              ;   Z = Y), Lst, 0, Sum).
于 2013-04-06T12:15:52.540 回答