從小寫起,寫下你所知道的。
simplify(plus(times(x,y),times(3 ,minus(x,y))),V,[x:4,y:2]):- V = 14.
是一個非常好的開始:(+ (* 4 2) (* 3 (- 4 2))) = 8 + 3*2 = 14
。但當然,
simplify(times(x,y),V,[x:4,y:2]):- V is 4*2.
更好。此外,
simplify(minus(x,y),V,[x:4,y:2]):- V is 4-2.
simplify(plus(x,y),V,[x:4,y:2]):- V is 4+2.
simplify(x,V,[x:4,y:2]):- V is 4.
所有完美的Prolog代碼。但當然我們真正的意思,很明顯,是
simplify(A,V,L):- atom(A), getVal(A,L,V).
simplify(C,V,L):- compound(C), C =.. [F|T],
maplist(simp(L), T, VS), % get the values of subterms
calculate(F, VS, V). % calculate the final result
simp(L,A,V):- simplify(A,V,L). % just a different args order
等getVal/3
將需要從L
列表方式校驗值,並calculate/3
實際進行計算,給定一個象徵性的操作名稱和計算值的列表。
研究maplist/3
和=../2
。
(未完成,未經測試)。
OK,maplist
是矯枉過正,因爲是=..
:所有的條款可能會是這樣的形式op(A,B)
的。這樣的定義可以簡化到
simplify(plus(A,B),V,L):-
simplify(A,V1,L),
simplify(B,V2,L),
V is V1 + V2. % we add, for plus
simplify(minus(A,B),V,L):-
% fill in the blanks
.....
V is V1 - V2. % we subtract, for minus
simplify(times(A,B),V,L):-
% fill in the blanks
.....
V is .... . % for times we ...
simplify(A,V,L):-
number(A),
V = .... . % if A is a number, then the answer is ...
,最後的可能性是,x
或y
等,滿足atom/1
。
simplify(A,V,L):-
atom(A),
retrieve(A,V,L).
因此,從上述條款的最後一次通話可能看起來像retrieve(x,V,[x:4, y:3])
,或者它可能看起來像retrieve(y,V,[x:4, y:3])
。這應該是一個直接的事情來執行。
你有沒有寫過你能顯示的任何代碼?它不是這個社區爲人們編寫代碼的做法。 – Brad 2013-03-01 04:06:22
@Brad除了我寫的一種方法,沒有。這是一個測試評估問題,並且仍然難以解釋如何解決這個問題。在我思考的過程中,我越來越困惑......朝着正確的方向努力將會受到重視。 – user2121487 2013-03-01 23:08:02
你將要遞歸調用左和右表達式樹的簡化,並使用結構名稱(times,plus等)適當地組合這些值。您會將變量列表傳遞給每個調用。這就是我可以從評論框的範圍內真正給出的所有提示。 – 2013-03-01 23:35:19