MNikolovski

Prolog Part4 - Lists, Pairs and the Member Function

Oct 29th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. Pairs and Lists is a great way to manipulate and store certain data, especially for recursive functions.
  2.  
  3. ex: [rob,john,lisa,conner].
  4. [josh,jake,eats(cheese)].
  5.  
  6. The arrays follow a basic structure:
  7. - The first element in the list is the HEAD, and then we logically denote the separation between the head and the rest of the list
  8. with a vertical bar '|';
  9. - The remaining items are the TAIL;
  10.  
  11. [Head|Tail]
  12.  
  13. Only non-empty lists can have a head and a tail.
  14.  
  15.  
  16. ex1: If we type the following in a query: ?- [Head|Tail] = [mirko, josh, jake, elisa, don, likes(jake, cars)].
  17. It is going to print the following: Head = mirko,
  18. Tail = [josh, jake, elisa, don, likes(jake, cars)]
  19.  
  20. ex2: But the following query: ?- [FirstItem, SecondItem | Tail] = [mirko, josh, jake, elisa, don, likes(jake, cars)].
  21. Is going to print the following: FirstItem = mirko,
  22. SecondItem = josh,
  23. Tail = [jake, elisa, don, likes(jake, cars)]
  24.  
  25. ex: Query: ?- [_, _, [_|X] | _] = [[], dead(z), [2, [b,c]], [], z, [2, [b,c]]].
  26. Output: X = [[b,c]]
  27.  
  28.  
  29. ### The Member Function ###
  30.  
  31. The member function is a recursive function.
  32.  
  33. member(X, [X|T]). ---> The termination condition (means, if the member we are looking for is the head, return true and stop)
  34.  
  35. member(X, [H|T]):-
  36. member(X,T). ---> This means, if the element is not in the head, search in the tail. After this function is called, the first
  37. element in the tail will become the head element of the new list, and it will check again for the (now new)
  38. head of the list.
Add Comment
Please, Sign In to add comment