文章目錄
- 求和
- 偶數求和與奇數求和
- 内置的處理函數
求和
- prolog中沒有傳回值
- 遞歸用得特别多
- 使用trace了解棧函數調用過程,notrace
部分參考
%終止條件
sum([], 0).
%遞歸條件
sum([H|T], X) :-
sum(T, X1),%可以認為做了一次查詢,并不是條件。
X is X1 + H.%
偶數求和與奇數求和
判斷奇偶的時候,
To decide if a number is even or odd, you can use the built-in Prolog operator N mod M, which computes the remainder after dividing the whole number N by the whole number M. Thus a number N is even if the goal 0 is N mod 2 succeeds. Remember that arithmetic expressions like X + 1 and N mod M are only evaluated, in Prolog, if they appear after the is operator. So 0 is N mod 2 works, but N mod 2 is 0 doesn't work.
必須用
0 is N mod 2
,這是才是做相等的判斷。就不是指派的感覺,如果是
N mod 2 is 0
,有一種找到N的變量,使得N餘2等于0,指派的感覺。
如果想把變量寫在前面,那可以用其他的表示符号:
=:=
判斷左右是否相等的。not再取反,isodd可以作為一個判斷是否奇數的函數。
isOdd(X) :-
not((X mod 2) =:= 0).
内置的處理函數
|
append()