问题描述:

I am trying to solve some prolog exercises in order to learn the language and i have problem adding the numbers in a prolog list.

For example i have the list [1,2,3] and i want to have as output number 6.

I wrote this code but it is not working.

list_adder([H|T],S):- S is H + T.

can anyone explain why?

网友答案:

try this:

list_adder([ ],0).
list_adder([X|L],Sum) :- list_adder(L,SL), Sum is X + SL.
网友答案:

It's because H + T in the example is matched with 1 + [2, 3], which doesn't mean anything. You should process the [2, 3] further, as shown in Fourth's answer.

网友答案:

list_adder(L,X),
        list_adder(L,[],X).

list_adder([],L,X) :-
        length(L,X).
list_adder([N|R1],L1,X) :-
        length(L,N),
        append(L1,L,L2),
        list_adder(R1,L2,X).
相关阅读:
Top