开发者

Add even elements in Prolog- Problem with 'amt' variable

I'm trying to figure out how to add even elements in a list (i've studied examples but cant do it on my own yet, need your help in pinning down my lack of understanding to a specific area).

The input I used is start([1,2,3,4,5]). There is no compilation error, but I dont get any output. I'm not sure what the logical error is..could you please advise?

(please see below for the latest update, after revising my code, now it works, and the problem lies in the way I use 'amt', but I dont know why!)

Original code that didnt work:

start(X):- add(X,1,amt), write(amt).

add([],_,0).  
add([H|Tail],Cnt,amt):-
  T is (Cnt mod 2), T == 0, Cnt1 is Cnt + 1, add(Tail,Cnt1,Y), amt is H+Y; 

  T is (Cnt mod 2), T =\=0, Cnt1 is Cnt + 1, add(Tail, Cnt1, amt).

Latest Update:

I replaced 'amt' with a 'S', and it works! But why wldnt it work with 'amt'?

here's the revised code that works:

开发者_运维知识库
start(X):- add(X,1,S), write(S).

add([],_,0).  
add([H|Tail],Cnt,S):-
  T is (Cnt mod 2), T == 0, Cnt1 is Cnt + 1, add(Tail,Cnt1,Y), S is H+Y; 

  T is (Cnt mod 2), T =\=0, Cnt1 is Cnt + 1, add(Tail, Cnt1, S).

Thanks :)


Are you intending to display amt1?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜