在Prolog中,递归与任何其他语言中的递归几乎完全相同。Prolog的诀窍在于:
- 每个变量都是本地的,并且
- 一旦统一,变量就不再是变量。它们永远不会改变值。
这意味着您经常需要构建我称之为“工作”谓词的东西,以执行所需的实际工作并携带一个或多个变量作为工作存储。以下是对sum/2的实现,用于对整数列表求和:
sum( [] , 0 ).
sum( [X|Xs] , Total) :-
sum(Xs,X,Total).
sum( [], Total, Total ).
sum( [X|Xs] , Subtotal , Total ) :-
NewSubTotal is Subtotal + X ,
sum( Xs , NewSubTotal , Total ).
这里是一个使用 ANSI C 实现的代码,与上面的 Prolog 代码非常相似:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct listnode
{
int value ;
struct listnode *next ;
} LISTNODE ;
int sum_core( int subtotal , LISTNODE *list )
{
LISTNODE *head ;
LISTNODE *tail ;
int list_item ;
if ( list == NULL ) return subtotal ;
head = list ;
tail = list->next ;
list_item = head->value ;
return sum_core( subtotal + head->value , tail ) ;
}
int sum( LISTNODE *list )
{
LISTNODE *head ;
LISTNODE *tail ;
int list_item ;
if ( list == NULL ) return 0 ;
head = list ;
tail = list->next ;
list_item = head->value ;
return sum_core( list->value , tail ) ;
}
int main ( int argc , char * argv[] )
{
LISTNODE *list ;
int total ;
list = malloc(sizeof(LISTNODE)) ; list->value = 1 ;
list->next = malloc(sizeof(LISTNODE)) ; list->next->value = 2 ;
list->next->next = malloc(sizeof(LISTNODE)) ; list->next->next->value = 3 ;
list->next->next->next = NULL ;
total = sum( list ) ;
return ;
}