Advertisement
obernardovieira

Fifteen Minutes to Wapner (day2) [SLiSW]

Aug 6th, 2015
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.68 KB | None | 0 0
  1. %some exercises (not all are from the book, And I had not done the last one from the book)
  2.  
  3. %compress
  4. compress([], []).
  5.  
  6. compress([X], [X]).
  7.  
  8. compress([X, X|Tail], Result) :-
  9.     compress([X|Tail], Result).
  10.  
  11. compress([X, Y|Tail], [X|Result]) :-
  12.     compress([Y|Tail], Result).
  13.  
  14. %size of list
  15. sizeOfList([],0).
  16.  
  17. sizeOfList([Head|Tail], N) :-
  18.     sizeOfList(Tail, N1), N is N1 + 1.
  19.  
  20. %element at position
  21. elementAt(0, [Head|_], Head).
  22.  
  23. elementAt(Pos, [_|Tail], Res) :-
  24.     Pos1 is Pos - 1,
  25.     elementAt(Pos1, Tail, Res).
  26.  
  27. %last number of list
  28. lastNumber([List], List). %[List] is a list with just one element
  29.  
  30. lastNumber([_|Tail], N) :- lastNumber(Tail, N). % should ignore Head at the begining
  31.  
  32. %flatten list (example below)
  33. %my_flatten([a, [b, [c, d], e]], X).
  34. %X = [a, b, c, d, e]
  35. myFlatten(Element,[Element]) :- \+ is_list(Element).
  36.  
  37. myFlatten([], []).
  38.  
  39. myFlatten([Head|Tail], Result) :-
  40.     myFlatten(Head, Result1), myFlatten(Tail, Result2), append(Result1, Result2, Result).
  41.  
  42. %reverse a list
  43.  
  44. reverseList(List, Reversed) :-
  45.     reverseList(List, [], Reversed).
  46.  
  47. reverseList([], Reversed, Reversed).
  48.  
  49. reverseList([Head|Tail], TheOther, Reversed) :-
  50.     reverseList(Tail, [Head|TheOther], Reversed).
  51.    
  52. %after 2 days, a new method to reverse a list
  53. reverseList([Element], [Element]).
  54.  
  55. reverseList([Head|Tail], Result) :-
  56.     reverseList(Tail, Result1), append(Result1, [Head], Result).
  57.  
  58. %smallest in list
  59. smallest([TheSmall], TheSmall).
  60.  
  61. smallest([Head|Tail], Res) :-
  62.     smallest(Tail, Res1), Head > Res1 -> Res is Res1; Res is Head. % or ... smallest(Tail, Res1), Res is min(Head, Res1).
  63.  
  64. %sum list
  65. sumList([],0).
  66. sumList([Head|Tail], N) :-
  67.     sumList(Tail, N1), N is N1 + Head.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement