Processing math: 100%

Lesson goal: Looking for Triangles

Previous: Reasoning about points and lines (2) | Home | Next: Looking for rectangles

Continuing to work with the set of (x,y) points from this lesson, let's look for some triangles amongst the points.

On the one hand, it's kind of easy to find triangles, because any 3 points will form a triangle. But, we still want Prolog to do it, so we'll get a bit of practice with it. The goal goal: line([P1,P2]), line([P2,P3]), line([P3,P1]). will find triangles, noting that we ask Prolog to look for 3 lines that are formed solely of 3 unique points (P1, P2 and P3). Notice we did not do line([P1,P2]), line([P3,P4]), line([P5,P6]).

To make Prolog work a little harder, suppose we restricted our triangle search to right triangles? Right triangles also need the three lines the goal above finds, with the additional qualification that two of the 3 lines are perpendicular.

Take a look at the goal below.

Now you try. Run the goal and test (with pencil, paper and a ruler by plotting the lines) if indeed the lines form right triangles.

Type your code here:

26
 
1
point(-4,4).
2
point(-3,2).
3
point(-1,1).
4
point(0,0).
5
point(-3,0).
6
point(1,3).
7
point(3,3).
8
point(-4,-4).
9
point(3,-3).
10
11
line([(X1,Y1),(X2,Y2)]) :- point(X1,Y1), point(X2,Y2), [X1,Y1] \= [X2,Y2].
12
13
horiz([(_,Y),(_,Y)]).
14
15
vert([(X,_),(X,_)]).
16
17
is_neg1(X) :- D is abs(X+1), D < 0.1.
18
19
perp(L1,L2) :- horiz(L1), vert(L2).
20
perp(L1,L2) :- vert(L1), horiz(L2).
21
perp(L1,L2) :- \+ vert(L1), \+ vert(L2), slope(L1,M1), slope(L2,M2), P is M1*M2, is_neg1(P).
22
23
slope([(X,_),(X,_)],infinite) :- !.
24
slope([(X1,Y1),(X2,Y2)],M) :- M is (Y2-Y1)/(X2-X1).
25
26
goal: line([P1,P2]), line([P2,P3]), line([P3,P1]), perp([P1,P2],[P2,P3]).

See your results here: