users-prolog
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Impressed but confused, gluing a list together...


From: Michał Bieliński
Subject: Re: Impressed but confused, gluing a list together...
Date: Tue, 1 Oct 2013 23:30:13 +0200
User-agent: SquirrelMail/1.4.21

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




reply via email to

[Prev in Thread] Current Thread [Next in Thread]