Prolog Practical Work  -  Week 2-3

An insect is crawling along a wire cube. It can only go left to right, back to front and top to bottom. We show this by giving a direction to the connections, so we call them arrows.

arrow(a,b).

arrow(a,c).

arrow(a,e).

arrow(b,d).

arrow(b,f).

arrow(c,d).

arrow(c,g).

arrow(d,h).

arrow(e,f).

arrow(e,g).

arrow(f,h).

arrow(g,h).

The insect can go from X to Y if there is a direct wire link from X to Y, or if there is a direct wire link to an intermediate point Z, from where it can go to Y. This can be defined as the following code in Prolog:

cango(X,Y):- arrow(X,Y).

cango(X,Y):- arrow(X,Z), cango(Z,Y).

 

 

copy and paste the above code into a file (or directly copy it from my file), and run

?- cango( a, Where).

Check how many solutions you can obtain.  ______________   (1 mark)

Explain why some solutions are appeared more than once. (1 mark)

 

Write a Prolog program cango2(X, Y, Steps) whose first two arguments work exactly same way as cango(X,Y). The extra argument represents how many steps needed from X to Y. For example, (3 marks)

 

?- cango2(a, b, N).

 

should return N=1, and

 

?- cango2(a, h, N).

 

should return N=3.

 

Before writing Prolog code, try to give an inductive definition for “cango2(X,Y,S)”, i.e. considering two cases: base case and inductive case.  (2 marks)