1

I need to write a recursion in prolog, which adds elements of two lists. Let's say we have a list, A = [a,b,c], and B = [d,e,f] and the final list, R, should look like this: R = [a+d, b+e, c+f].

I came up only with this:

xxx([a], [b], [a+b]).
xxx([H1|T1], [H2|T2], W) :- xxx(T1, T2, W), .(H1+H2, W). 

But it gives me uncaught exception: error(syntax_error('user_input:5 (char:15) expression or ] expected in list'),read_term/3). I also tried this:

xxx([a], [b], [a+b]).
xxx([H1|T1], [H2|T2], W) :- xxx(T1, T2, W), append(H1+H2, W, []). 

With no success: uncaught exception: error(syntax_error('user_input:4 (char:16) expression or ] expected in list'),read_term/3)

Im using Gnu prolog (gprolog)

1
  • Note that the dot operator . for building lists is usually hidden; you need to do some "trick" to be able to use it. This is probably what is giving the syntax error. Commented Dec 19, 2016 at 23:26

1 Answer 1

3
xxx([], [], []).
xxx([E|Es], [F|Fs], [E+F|EFs]) :-
   xxx(E, F, EFs).

or

..., maplist(ex, Es, Fs, EFs), ...

ex(E, F, E+F).

or

..., maplist(\E^F^(E+F)^true, Es, Fs, EFs), ...

using library(lambda)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.