问题
We are not supposed to use any of the functions other than the ones listed below:
- A single clause must be defined (no more).
+
,
;
.
!
:-
is
- Lists
- Head and tail syntax for list types
- Variables
For example sumlists([1,2,3,5,7],11)
then the program execution should print TRUE
. Because 1+3+7 (any three)=11 (given N value).
回答1:
Ideally, we either get an element or don't, as we go along the input list; and we stop either on having reached the needed sum, or having surpassed it, or when the list has been exhausted.
But we can only have one clause one predicate here, and only use certain primitives, so instead we sneakily use +
both symbolically, to gather the information for summation, and as an arithmetic operation itself:
sumlists(L, N) :-
N = X+A+B+C, X is A+B+C, !
; L = [H|T], sumlists(T, N+H)
; L = [H|T], sumlists(T, N).
来源:https://stackoverflow.com/questions/59207719/using-a-single-clause-compute-whether-the-sum-of-any-three-members-of-a-list-is