changeset 63:e159ec90a072

Day 2 self-study, with insert sort
author IBBoard <dev@ibboard.co.uk>
date Sat, 30 Sep 2017 14:26:58 +0100
parents 96e77f914f9b
children f6fce6a54e94
files 3-Prolog/day2-self-study.pl
diffstat 1 files changed, 26 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/3-Prolog/day2-self-study.pl	Sat Sep 30 14:26:58 2017 +0100
@@ -0,0 +1,26 @@
+% 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([], [], []).
+insert_sort([Head], [], [Head]).
+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).
\ No newline at end of file