开发者

Adding integers in list

开发者 https://www.devze.com 2023-04-12 21:46 出处:网络
For so开发者_如何学运维me reason, this is not working. I am getting: ERROR: is/2: Arguments are not sufficiently instantiated

For so开发者_如何学运维me reason, this is not working. I am getting: ERROR: is/2: Arguments are not sufficiently instantiated

1 add_list([]).
2 add_list([H|T]):-
3                 Sum2 is Sum1 + H,
4                 add_list(T).

I am trying to add the contents of a list (containing only numbers).


I'm not sure what you are trying to do. But if you are trying to calc total sum it will be this way (changed name to list_sum as add_list doesn't make any sense):

list_sum([], 0).
list_sum([H|T], Sum):-
    list_sum(T, SubSum),
    Sum is SubSum + H.


You can have a "functionnal mind" with foldl :

foldl(_P, [], V, V).

foldl(P, [H|T], V1, VF) :-
    call(P, H, V1, V2),
    foldl(P, T, V2, VF).


sum_list(L, S) :-
    foldl(add, L, 0, S).


add(X, Y, Z) :-
    Z is X+Y.


Alternatively you could also use an accumulator (the advantage is, that it is tail-recursive and therefore can be optimized)

list_sum(L,R) :- list_sum(L,0,R).   
list_sum([],A,A). 
list_sum([H|T],A,R) :- A1 is A + H, list_sum(T,A1,R).
0

精彩评论

暂无评论...
验证码 换一张
取 消