view 3-Prolog/day2-self-study.pl @ 76:5860845f5dac

Create module with synchronous translation and notes on how to run
author IBBoard <dev@ibboard.co.uk>
date Sat, 03 Feb 2018 20:25:47 +0000
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).