?- formula([3,15,17,20,1],3).
operation("+").

operation("-").

operation("/").

operation("x").

do_operation(A, "+", B, A+B).

do_operation(A, "-", B, A-B).

do_operation(A, "/", B, A/B).

do_operation(A, "x", B, A*B).

formula(L, Target) :-

findall(X, perm(L, X), PermList),

process_permutation(PermList, Target).

process_permutation([], _).

process_permutation([H|_], Target) :-

formula_acc(H, 0, [], Formula, Target),

write("Formula: "), pretty_print(Formula),

write("for a total of "), write(Target), nl.

process_permutation([_|T], Target) :-

process_permutation(T, Target).

formula_acc([], Total, Formula, Formula, Target) :-

Total =:= Target.

formula_acc([H|T], 0, [], Formula, Total) :-

formula_acc(T, H, [H], Formula, Total).

formula_acc([H|T], CurTotal, CurFormula, Formula, Total) :-

CurTotal > 0,

operation(O), do_operation(CurTotal, O, H, Result),

append(CurFormula, [O,H], NewFormula),

formula_acc(T, Result, NewFormula, Formula, Total).

append([], L, L).

append([H| L1], L2, [H| L3]) :-

append(L1, L2, L3).

pretty_print([]) :- nl.

pretty_print([H|T]) :-

write(H), write(" "), pretty_print(T).

perm(List,[H|Perm]):-delete(H,List,Rest),perm(Rest,Perm).

perm([],[]).