Anyway the exercises, trivially they can be answered thus :
| ?- reverse([12,4,5,7],SL).
SL = [7,5,4,12]
| ?- min_list([12,4,5,7],SL).
SL = 4
| ?- sort([12,4,5,7],SL).
SL = [4,5,7,12]
(1 ms) yes
But we ought to try a bit harder, so :
revappend([], Ys, Ys).
revappend([X|Xs], Ys, Zs) :- revappend(Xs, [X|Ys], Zs).
rev(Xs,Ys) :- revappend(Xs,[],Ys).
I pinched this in the end, after repeated attempts to use 'is' on something that isn't an arithmetic expression.
This one is all mine, alas. It's not tail-recursive so it would be inefficient. Here I have added a rule for each case -but it might be possible to use an 'if' statement.
smallest(A,[A|[]]).
smallest(S,[H|T]) :- smallest(Ss,T), H >= Ss, S is Ss.
smallest(S,[H|T]) :- smallest(Ss,T), H < Ss, S is H.
Finally the sort -I can't imagine that this is very efficient either, it works by taking the smallest member off the original list and putting it add the head of a new list, this happens repeatedly (through recursion) until the original list is empty :-
jsort([], Ys, Ys).
jsort(Xs, Ys, Zs) :- min_list(Xs,S), delete(Xs,S,X1s), jsort(X1s, [S|Ys], Zs).
sortj(Xs,Ys) :- jsort(Xs,[],Ys).
No comments:
Post a Comment