« Return to Thread: Destructive update of terms (from foreign code)

Re: Destructive update of terms (from foreign code)

by Jan Wielemaker-3 :: Rate this Message:

Reply to Author | View in Thread

On Friday 03 July 2009 05:21:52 pm Roberto Bagnara wrote:

> Hi there.
>
> I have the following problem and I don't know the best
> way to solve it.  I have a gigantic, ground Prolog term.
> In this term there are some subterms of the form
>
>         f(..., ..., ..., N)
>
> where N is a (small) integer.  The computation consists
> of three phases:
>
> 1) a traversal of the original gigantic term;
> 2) a second traversal which copies the original term
>     into a new term that is equal to the original apart
>     from the fact that some of the integers (N) have been
>     replaced by some other integers;
> 3) a traversal of the new, modified term.
>
> What happens is that:
>
> a) the copy of point (2) is too expensive;
> b) the original term is no longer needed after point (2);
> c) there is no backtracking involved.
>
> The obvious solution would be to avoid the copy in point (2)
> and replace it with a destructive update of the few integers
> that need to be changed.  I have read the documentation of
> setarg/3 and nb_setarg/3, and none seems to do what I want:
> setarg/3 does trailing, which I don't want;
> nb_setarg(+Arg, +Term, +Value) has the problem that
> "[if] Term is not atomic [which is my case], it is
> duplicated using duplicate_term/2", and this duplication
> is precisely what I want to avoid.
>
> Am I missing something?

I think the documentation is misleading. It should read `Value is not
atomic'. Replacing a small integer in a big term using nb_setarg/3 is
really cheap: it just destructively modifies the big term.

> Note that I am very willing to destructively modify the
> term using C/C++ code (actually, this would be even better
> for me).  And portability is not an issue.
> Thanks a lot for any hint,

It shouldn't be too hard to add a PL_nb_setarg(int, term_t, term_t)
as well, though I think this is a bit weird thing to do.  Maybe, if
you use this huge datastructure from Prolog and C, it is easier to
define a multi-dimensional array in C and provide access functions
to get elements from Prolog?

        Cheers --- Jan

_______________________________________________
SWI-Prolog mailing list
SWI-Prolog@...
https://mailbox.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog

 « Return to Thread: Destructive update of terms (from foreign code)