Michał, Thanks… it makes more sense when somebody else explains it if they know what they are talking about… one day I will know what I am talking about… one day...
:) On 1 Oct 2013, at 22:30, "Michał Bieliński" <[email protected]> wrote: > Dnia 1 Października 2013, 23:03, Wt, emacstheviking napisał: >> I am dong some gluing of strings together and I wanted an intercalate >> capability like many languagues offer, e.g. "join" in Javascript or >> implode() with PHP and I came up with this: >> >> join([], _, []). >> join([X], _, [X]). >> join([X|Xs], With, [X, With|Acc]) :- join( Xs, With, Acc). >> >> The great news is that I figured it out first time and it seems to >> do what I need, I also have a flatten() predicate that will produce >> the final output string. >> >> However... I am not sure I truly understand how I did it... if >> I explain my reasoning perhaps somebody can straighten me out? > > Okay. Lets have at it. > >> Rule 2: If there is a single X in the list, return just that single X. >> That avoid "trailing" glue. >> join([X], _, [X]). > > I added a cut to avoid the solution with trailing glue. > join([X], _, [X]) :- !. > >> Rule 3: Um...... I used the force I guess. >> join([X|Xs], With, [X, With|Acc]) :- glue( Xs, With, Acc). > > Having a list of at least two elements, a "With" (glue) to separate return > the following: a list with the first element of what you started with, > then put the glue and next ... well, to know what comes next you have to > repeat the operation with tail of the very first list. The result of that > step will tell you what to put next. > > Thus first call rips the first character ("head") from the string, makes > it the beginning of new list and puts glue next. Then the "decapitated" > string is passed to new invocation of join predicate which repeats the > process with string shorter by one character building the final return > stage by stage. Recurse until there is only once character left. > > Knowing this maybe you could build join so that flatten is not needed. > Assuming you want it of course. > > -- > Michał Bieliński > > > _______________________________________________ > Users-prolog mailing list > [email protected] > https://lists.gnu.org/mailman/listinfo/users-prolog _______________________________________________ Users-prolog mailing list [email protected] https://lists.gnu.org/mailman/listinfo/users-prolog
