Advertisement
Guest User

Untitled

a guest
Jul 12th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.82 KB | None | 0 0
  1. % http://www.swi-prolog.org/pldoc/man?section=lists
  2.  
  3. % Import basic list functionality
  4. :- use_module(library(lists)).
  5.  
  6. % These lists wont work, why not?
  7. append([40,7,9,8],[1],list).
  8. append([1],[3,5],l2).
  9.  
  10.  
  11. ssort(L,LS) :-
  12.     ssortStartLoop(L,LS).
  13.  
  14. % Need to start the loop and append to an _empty_ list
  15. % Input list L, output list LS
  16. ssortStartLoop(L,LS) :-
  17.     lowestFirst(L,L1),
  18.     L1 = [H|T],
  19.     append([],H,SortedTemp),
  20.     ssortRecursive(T,SortedTemp,LS).
  21.  
  22. % Put the lowest element first, rest unordered
  23. % Input list L, output list L1
  24. lowestFirst(L,L1) :-
  25.     findLowest(L,Lowest),
  26.     addRest(Lowest,L,L1).
  27.  
  28. % Finds the lowest value Lowest from input list L
  29. findLowest(L,Lowest) :-
  30.     L = [H|T],
  31.     loopListLowest([H|T],Lowest).
  32.  
  33. % Different variants of looping over the list
  34. % Input X is the lowest enountered value so far
  35. % Tail is the elements that are not checked yet
  36.  
  37. % X is lowest, include X in next iteration
  38. loopListLowest([X|Tail],Lowest) :-
  39.     Tail = [H|T],
  40.     X < H,
  41.     loopListLowest([X|T],Lowest).
  42.  
  43. % H is lowest (or the same), include H in next iteration
  44. loopListLowest([X|Tail],Lowest) :-
  45.     Tail = [H|T],
  46.     X >= H,
  47.     loopListLowest([H|T],Lowest).
  48.  
  49. % No more elements to check (tail is empty)
  50. % X is the lowest value
  51. loopListLowest([X|[]],Lowest) :-
  52.     Lowest = X.
  53.  
  54.  
  55. % Remove Lowest from the list, and add it as the first element
  56. addRest(Lowest,L,L1) :-
  57.     select(Lowest,L,RestOfL),
  58.     append([Lowest],RestOfL,L1).
  59.  
  60.  
  61. %
  62. ssortRecursive(L,SortedTemp,LS) :-
  63.     is_list(SortedTemp),
  64.     lowestFirst(L,L1),
  65.     L1 = [H|T],
  66.     append(SortedTemp,[H],SortedTemp2),
  67.     ssortRecursive(T,SortedTemp2,LS).
  68.  
  69. ssortRecursive(L,SortedTemp,LS) :-
  70.     integer(SortedTemp),
  71.     lowestFirst(L,L1),
  72.     L1 = [H|T],
  73.     append([SortedTemp],[H],SortedTemp2),
  74.     ssortRecursive(T,SortedTemp2,LS).
  75.  
  76. ssortRecursive([],SortedTemp,LS) :-
  77.     LS = SortedTemp.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement