Using a single clause compute whether the sum of any three members of a list is equal to given value

爷,独闯天下 提交于 2020-01-03 01:22:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!