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