R – Given [1,2,3] in prolog get back [6,5,3] by reverse accumalation

prolog

Q. Given [1,2,3] in Prolog get back [6,5,3] by reverse accumulation

I have the start code:

accumalate([H],[H]).
accumalate([H1 | H2], [Hnew, H2]),
       Hnew is H1 + H2.

….

I am looking for basic Prolog solution.

Best Answer

We are not here to do you homework for you. So the best we can do is provide you with some tips. So ask yourself these questions:

  1. What are the base cases here (for which inputs is the output immediate)?
    • You have accumulate([N], [N])., but what about empty lists?
  2. In what order must the additions be performed?
  3. More specifically, which elements must be added first?

Other than that, I can tell you that you can solve this using three clauses. No other predicates required. Good luck!

Bonus: you may want to define the head of the recursive clause as follows:

accumulate([N|T], [N1,N2|T2]).
Related Topic