maximum([A],A,N,N,A).
maximum([H|T],A,N,Posneu,Last):-
NN is N+1,
maximum(T,B,NN,Pos,Last),
( H>B
-> A=H,
Posneu = N
; A=B,
Posneu = Pos).
pancakesort([], []).
pancakesort(L, Lsort):-
maximum(L,Max,1,PosMax,Last),
( Last == Max
-> append(Lwo,[Max],L)
; length(Ltmp,PosMax),
append(Ltmp,Ltmp1,L),
reverse(Ltmp,Pmtl),
append(Pmtl,Ltmp1,[Max|Owl]),
reverse(Owl,Lwo)
),
pancakesort(Lwo,LwoSort),
append(LwoSort,[Max],Lsort).
?- pancakesort([1,4,2,6],L).
L = [1, 2, 4, 6] ;
false.
So the idea in each iteration/recursion step is to find the maximum, flip the heap which contains the maximum as last element so that the largest pancake is on top and then to flip it again so that the largest pancake is on the bottom. Repeat with the pancake heap without the lower most pancake.
So for my implementation I need a helper predicate maximum/5 which searches for the maximum in a list and returns the position of the maximum as well. To make it a bit more efficient it also returns the last element so that the program check first if the largest pancake is already on the bottom (Last == Max). If this is not the case the first PosMax pancakes (Ltmp) are seperated from the heap, flipped (reverse(Ltmp,Pmtl)) and put back on the heap. Now the largest pancake lies on top ([Max|Owl]), so the whole heap has to be flipped (reverse(Owl,Lwo)). Since the largest pancake will be removed it is easier to remove it before flipping. Now the procedure is repeated for the unsorted heap getting a sorted subheap. Append the maximium element at the end and you got a sorted list. If there are no pancakes on the heap left, the heap is sorted (pancakesort([], []).)
A more compact but also more inefficient implementation would ignore the test for the case if the largest pancake is already at the bottom:
maximum([A],A,N,N).
maximum([H|T],A,N,Posneu):-
NN is N+1,
maximum(T,B,NN,Pos),
( H>B
-> A=H,
Posneu = N
; A=B,
Posneu = Pos).
pancakesort([], []).
pancakesort(L, Lsort):-
maximum(L,Max,1,PosMax),
length(Ltmp,PosMax),
append(Ltmp,Ltmp1,L),
reverse(Ltmp,Pmtl),
append(Pmtl,Ltmp1,[Max|Owl]),
reverse(Owl,Lwo),
pancakesort(Lwo,LwoSort),
append(LwoSort,[Max],Lsort).