From cb53d087b23da10259d9ecb9faf2a221956b0b07 Mon Sep 17 00:00:00 2001 From: Costa Vitor Date: Fri, 24 Aug 2012 15:19:15 -0500 Subject: [PATCH] add rb_fold/4. --- docs/yap.tex | 11 +++++++++++ library/rbtrees.yap | 26 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/docs/yap.tex b/docs/yap.tex index 377050407..fb8847c55 100644 --- a/docs/yap.tex +++ b/docs/yap.tex @@ -10910,6 +10910,17 @@ holds, then the value associated with @var{Key} in @var{TN} is @var{ValF}. Fails if or if @code{call(G,Val0,ValF)} is not satisfiable for all @var{Var0}. Assumes keys are not repeated. +@item rb_fold(+@var{T},+@var{G},+@var{Acc0}, -@var{AccF}) +@findex rb_fold/4 +@snindex rb_fold/4 +@cnindex rb_fold/4 + For all nodes @var{Key} in the tree @var{T}, if the value +associated with key @var{Key} is @var{V} in tree @var{T}, if +@code{call(G,V,Acc1,Acc2)} holds, then if @var{VL} is value of the +previous node in inorder, @code{call(G,VL,_,Acc0)} must hold, and if +@var{VR} is the value of the next node in inorder, +@code{call(G,VR,Acc1,_)} must hold. + @item rb_clone(+@var{T},+@var{NT},+@var{Nodes}) @findex rb_clone/3 @snindex rb_clone/3 diff --git a/library/rbtrees.yap b/library/rbtrees.yap index 9bb606046..aa1734cb3 100644 --- a/library/rbtrees.yap +++ b/library/rbtrees.yap @@ -30,6 +30,7 @@ rb_map/2, rb_map/3, rb_partial_map/4, + rb_accumulate/4, rb_clone/3, rb_clone/4, rb_min/3, @@ -820,6 +821,31 @@ map(black(L,_,V,R),Goal) :- map(L,Goal), map(R,Goal). +:- meta_predicate rb_accumulate(?,3,?,?). % this is required. +:- meta_predicate map_acc(?,3,?,?). % this is required. + +%% rb_fold(+T, :G, +Acc0, -AccF) is semidet. +% +% For all nodes Key in the tree T, if the value associated with +% key Key is V in tree T, if call(G,V,Acc1,Acc2) holds, then +% if VL is value of the previous node in inorder, +% call(G,VL,_,Acc0) must hold, and +% if VR is the value of the next node in inorder, +% call(G,VR,Acc1,_) must hold. + +rb_fold(t(_,Tree), Goal, In, Out) :- + map_acc(Tree, Goal, In, Out). + +map_acc(black('',_,_,''), _, Acc, Acc) :- !. +map_acc(red(L,_,V,R), Goal, Left, Right) :- + map_acc(L,Goal, Left, Left1), + once(call(Goal,V, Left1, Right1)), + map_acc(R,Goal, Right1, Right). +map_acc(black(L,_,V,R), Goal, Left, Right) :- + map_acc(L,Goal, Left, Left1), + once(call(Goal,V, Left1, Right1)), + map_acc(R,Goal, Right1, Right). + %% rb_clone(+T, -NT, -Pairs) % % "Clone" the red-back tree into a new tree with the same keys as