Here is an implementation based on deBruijn indexes, and
based on the Prolog answers here . The first part,
translating L[_] from wikipedia into deBruijn indexes gives:
lambda(P*Q, W) :-
lambda(P, R),
lambda(Q, S),
simplify(R, S, W).
lambda('I', b(0)).
lambda('K', b(b(1))).
lambda('S', b(b(b(2*0*(1*0))))).
The new predicates in the linear simplification are simplify/2, subst2/4, notin/2 and oncein/2. shift/4 is exactly as in the Prolog
answers here. The predicate subst2/4 in contrast to subst/4
calls simplify/2 to build application terms:
simplify(b(R), _, S) :- notin(R, 0), !,
shift(R, 0, -1, S).
simplify(b(R), S, T) :- oncein(R, 0), !,
subst2(R, 0, S, T).
simplify(R, S, R*S).
subst2(P*Q, J, D, W) :- !,
subst2(P, J, D, R),
subst2(Q, J, D, S),
simplify(R, S, W).
subst2(b(P), J, D, b(R)) :- !,
K is J+1,
subst2(P, K, D, R).
subst2(J, K, _, J) :- integer(J), J < K, !.
subst2(0, 0, D, D) :- !.
subst2(J, J, D, R) :- integer(J), !,
shift(D, 0, J, R).
subst2(J, _, _, K) :- integer(J), !, K is J-1.
subst2(I, _, _, I).
The predicates notin/2 and oncein/2 split the "at most once"
into "not" and "exactly once":
notin(P*Q, J) :- !,
notin(P, J),
notin(Q, J).
notin(b(P), J) :- !,
K is J+1,
notin(P, K).
notin(J, K) :- integer(J), !,
J =\= K.
notin(_, _).
oncein(P*Q, J) :-
notin(P, J), !,
oncein(Q, J).
oncein(P*Q, J) :- !,
oncein(P, J),
notin(Q, J).
oncein(b(P), J) :- !,
K is J+1,
oncein(P, K).
oncein(J, J).
This is the question problem solved:
?- lambda('S'*('S'*('K'*('S'*('K'*'S')*'K'))*'S')*('K'*'K'), X).
X = b(b(b(2*0*1)))
The example doesn't completely converse with this bracket abstraction here:
?- unlambda(b(b(b(2*0*1))), X).
X = 'S'*('S'*('K'*'S')*('S'*('K'*'K')*'S'))*('K'*'K')