2013-12-08 75 views
0

我想問一下關於序言編程。我有:在序言中計數重複項

byCar(auckland,hamilton). 
byCar(valmont,metz). 

byTrain(metz,frankfurt). 

byPlane(frankfurt,bangkok). 
byPlane(bangkok,auckland). 

travell(From,To,go(From,To,car)) :- byCar(From,To). 
travell(From,To,go(From,To,train)) :- byTrain(From,To). 
travell(From,To,go(From,To,plane)) :- byPlane(From,To). 
travell(From,To,go(From,Step,Via,Go)) :- travell(From,Step,go(From,Step,Via)),travell(Step,To,Go). 

然後我問winprolog:

?- travell(valmont,hamilton,Go). 

它回答

Go = go(valmont,metz,car,go(metz,frankfurt,train,go(frankfurt,bangkok,plane,go(bangkok,auckland,plane,go(auckland,hamilton,car))))) 

我的問題是,是否有可能算多少 '走出去' 能有多少?就像我之前的例子,它有5'去'

回答

-1

會更容易,如果你可以統一go/3和去/ 4 arity。無論如何,請嘗試

count_last_arg(Struct,Func,Count) :- 
    count_last_arg(Struct,Func,0,Count). 

count_last_arg(Struct,Func,N,Count) :- 
    Struct =.. L, last(L, LL), LL =.. [Func|_] 
    -> N1 is N+1, 
    count_last_arg(LL,Func,N1,Count) 
    ; Struct =.. [Func|_] 
    -> Count is N+1 
    ; Count is N. 
+0

嗯....我的知識還沒有達到這個水平呢......有沒有其他更簡單的方法?無論如何,我會嘗試... –