Guest User

Untitled

a guest
Jan 15th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 2.41 KB | None | 0 0
  1. % This is the general append function that defines a relationship between 3 lists, where
  2. % list 3 is the product of sticking list 1 and list 2 together. As Prolog does not 'return'
  3. % values, you can use append in any which way you like by specifying which of these 3 lists
  4. % is unknown (or more than 1 unknown if you like), not just L3.
  5.  
  6. % Base case, an empty list + any list is just that list.
  7. append([],L2,L2).
  8. % General case. L1 is represented here as X (head) and L1t (tail)
  9. % L2 is represented in full as L2.
  10. % L3 is represented as X (same X as above, this is important) and L3t (tail).
  11. % So this defines the relation where L1's tail + L2 is L3's tail, and L1's head = L3's head.
  12. % Think about it, this makes sense:
  13. %     L1 = [1, 2]
  14. %     L2 = [3, 4]
  15. %     L3 = [1, 2, 3, 4]
  16. % L1 and L3 always have the same head. And what is the tail of L3? [2, 3, 4]
  17. % It is the tail of L1 [2] appended with L2 [3, 4].
  18. append([X|L1t],L2,[X|L3t]) :-
  19.     append(L1t,L2,L3t).
  20.  
  21. % This one's for Ben. I haven't tested it so it may not be valid but the idea is there.
  22. % Generate a list of zeroes. 'zeroes' defines a relationship between a number and a list
  23. % which holds if that list is a list containing that number of zeroes. The base case is
  24. % simple (and can be written in a multitude of ways, this being the shortest):
  25. zeroes(1, [0]).
  26. % That simply states that zeroes(1, [0]). is valid.
  27.  
  28. % Here is the general case for X zeroes in list L. We will define it as the appending
  29. % of a zero to the list found by zeroes(X - 1, ?).
  30. zeroes(X, L) :-
  31.     X2 is X - 1,        % Here we can make a variable for the hell of it.
  32.     zeroes(X2, L2),     % Find the list L2 that satisfies the condition of one less zero than required.
  33.     append(L2, [0], L). % Here we state for the rule to be true/complete/succeed we need
  34.                         % to find L (still unknown) such that appending [0] to L2 (known) gives it.
  35.                         % It is not really a function call, it is a condition, they all are!
  36.                         % The fact that we use verbs for rule names is confusing but done
  37.                         % for brevity. Really it could be like listAandBmakeC(A, B, C); i.e.
  38.                         % a rule like isAPerson(X) .. if that helps at all.
  39.                        
  40. % Now as soon as you use 'is', the function becomes irreversible, I believe, so you can't do
  41. % zeroes(HowMany, [0, 0, 0]).
  42. % and get
  43. % HowMany = 3.
Add Comment
Please, Sign In to add comment