view 3-Prolog/day2-self-study.pl @ 99:67631cb2ea48

Expand the last note on getting into the monad state
author IBBoard <dev@ibboard.co.uk>
date Sun, 30 Jun 2019 16:15:33 +0100
parents f6fce6a54e94
children
line wrap: on
line source

% Skipping Towers of Hanoi - need to think how to map it to rules when it is about movement.
%
% Reversing a list
reverse_list([], []).
reverse_list([Head], Reversed) :- Reversed = [Head].
reverse_list([Head1|Tail], Reversed) :- reverse_list(Tail, ReversedTail), append(ReversedTail,[Head1], Reversed).

% Finding the smallest element
% Remember: Prolog evaluates both sides, so a rule with "Head > Holder" first only happens if
% that statement is true!
find_smallest([], Smallest, Smallest).
find_smallest([Head|Tail], Holder, Smallest) :- Head > Holder, find_smallest(Tail, Holder, Smallest).
find_smallest([Head|Tail], Holder, Smallest) :- Head =< Holder, find_smallest(Tail, Head, Smallest).
% And give the user a sensible version that doesn't need them to supply an arbitrary (potentially wrong)
% initial value
find_smallest([Head|Tail], Smallest) :- find_smallest([Head|Tail], Head, Smallest).

% Sort a list
insert_sort([], Sorted, Sorted).
insert_sort([UHead|UTail], [], Result) :- insert_sort(UTail, [UHead], Result).
insert_sort([UHead|UTail], [SHead|STail], Result) :- UHead > SHead, insert_sort([UHead], STail, NewSTail), insert_sort(UTail, [SHead|NewSTail], Result).
insert_sort([UHead|UTail], [SHead|STail], Result) :- UHead =< SHead, insert_sort(UTail, [UHead|[SHead|STail]], Result).
% Friendly user version
insert_sort([UHead|UTail], Result) :- insert_sort([UHead|UTail], [], Result).