Advertisement
sb8623

list.pl

Apr 18th, 2023
2,266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.69 KB | Source Code | 0 0
  1. % Given a list L we want to find wether an element X is a member of that list or not.
  2.  
  3. member(X, [X | _ ]).
  4.  
  5. member(X, [Y | Rest]):-
  6.     member(X, Rest).
  7.  
  8. % Concatenate list L1 and L2 to form list L3
  9.  
  10. concat([], L, L).
  11.  
  12. concat([X|L1], L2, [X|L3]):-
  13.     concat(L1, L2, L3).
  14.  
  15. member1(X, L):-
  16.     concat(L1, [X|L2], L).
  17.  
  18. % adding an item X to the beginning of a list L
  19.  
  20. add(X, L, [X|L]).
  21.  
  22. %delete the first occurence of the element X of a list L
  23. del(X, [X|L], L).
  24. del(X, [Y|Rest], [Y|L1]):-
  25.     del(X, Rest, L1).
  26.  
  27. del_all(X, [], []).
  28. del_all(X, [X|L], L1):-
  29.     del_all(X, L, L1).
  30. del_all(X, [Y|L], L1):-
  31.     del_all(X, L, L2),
  32.     concat([Y], L2, L1).
  33.  
  34. %find out the last member of a list.
  35. lastmember([X], X).
  36. lastmember([_|L], X):-
  37.     lastmember(L, X).
  38.  
  39. %find the reverse of a list
  40. reverselist([], []).
  41. reverselist([X], [X]).
  42. reverselist([X | L], L1):-
  43.     reverselist(L, L2),
  44.     concat(L2, [X], L1).
  45.  
  46. %check palindrome of a list
  47. palindrome(L):-
  48.     reverselist(L, L).
  49.  
  50. %insert in X in all possible positions
  51. insert_all_pos(X, [], [X]).
  52. insert_all_pos(X, [Y|T], [X,Y|T1]):-
  53.     insert_all_pos(X, T, T1).
  54.  
  55. %check palindrome using concatenate
  56. palindrome1([]).
  57. palindrome1([_]).
  58. palindrome1([H|T]):-
  59.     concat(L, [H], T),
  60.     palindrome1(L).
  61.  
  62. %check whether a list is of odd length
  63. even([]).
  64. odd([_]).
  65. even([H|T]):-
  66.     odd(T).
  67. odd([H|T]):-
  68.     even(T).
  69.  
  70. %find out the length of a list
  71. length([], 0).
  72. length([X|Y], N):-
  73.     length(Y, N1),
  74.     N1 is N-1.
  75.  
  76. %find all prefixes and suffixes of a list
  77. prefix([], L).
  78. prefix([X|Y], [X|Y1]):-
  79.     prefix(Y, Y1).
  80.  
  81. suffix(L, L).
  82. suffix(L1, [_|L2]):-
  83.     suffix(L1, L2).
  84.  
  85. %find all permutations of a list
Tags: pl
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement