I’m trying to better grok difference lists. I’d like to use them for the below predicate. Currently it’s using recursion with an accumulator. This creates a stack, which reverses the order that’d I’d like them to be in.
indices_elems(Is, Ls, Es) :- indices_elems(Is, Ls, [], Es).
indices_elems([], _, Es, Es).
indices_elems([I|Is], Ls, Acc, Es) :-
nth1(I, Ls, E),
indices_elems(Is, Ls, [E|Acc], Es).
:- findall(X, between(1,100,X), Xs), indices_elems([7,11,13,97], Xs, Es).
Xs = [1,2,3,...,99,100],
Es = [97,13,11,7].
I’ve heard that difference lists create a natural queue, but haven’t been able to figure out how to implement one; and all resources I’ve seen seem to shroud the whole idea in further mystery.
Of course, I could slap a reverse/2
at the end and be happy that my needs are met, but I’d rather use Prolog to its fullest. And also, I concede that this predicate doesn’t meet full generality. So any help along those lines also appreciated.
Ideally,
:- findall(X, between(1,100,X), Xs), indices_elems([7,11,13,97], Xs, Es).
would return Es = [7,11,13,97]
while using a difference list.
Much appreciated!