M-Amr Moussa
M-Amr Moussa

Reputation: 107

Prolog doesn't pass variables

In a Prolog rule, I tried to pass variable from case to another but it doesn't work

plane(c130,propeller,high,conventional,conventional,under-wing).
plane(c141,jet,high,sweptback,ttail,upperwing).
plane(c5a,jet,high,sweptback,ttail,none).
plane(b747,jet,low,sweptback,conventional,aftcockpit).

planeinfo:-
    plane(Name,Eng,Wing,Shape,Tail,Bulges),
    write(Name),put(10),
    write(Eng),put(10),
    write(Wing),put(10),
    write(Shape),put(10),
    write(Tail),put(10),
    write(Bulges).

getplane:-
    write('enter engine type '),
    read(Eng),
    Eng == 'propeller' ,Name ='c130',
    planeinfo,!;
    write('enter wing postion'),
    read(Wing),
    Wing == 'low' , Name = 'b747',
    planeinfo,!;
    write('enter the bulges type'),
    read(Bulges),
    Bulges == 'upperwing' , Name = 'c141', write(Eng),write(Wing),
    planeinfo,!;
    write('enter wing shape'),
    read(Shape),
    write('enter tail'),
    read(Tail),
    planeinfo,
    write("Plane Is Not Found , Please Retry"),
    repeat.

and here is the output

?- getplane.
enter engine type jet.
enter wing postion|: high.
enter the bulges type|: upperwing.
_L155_L156c130

propeller
high
conventional
conventional
under-wing
true.

in addition to a wrong output .

Upvotes: 1

Views: 88

Answers (1)

max66
max66

Reputation: 66230

I tried to pass variable from case to another but it doesn't work

It's because the or operator (;, post the first planeinfo,!) activate the backtracking and cancel the effect of the first read/1.

If you want to maintain the read values for engine (Eng), wing (Wing) and bulges (Bulges), you have to work with parentheses to limit the backtracking effect of the ; operator.

Not sure about what do you want obtain but... the following is an example

getplane:-
  write('enter engine type '),
  read(Eng),
  (  Eng == 'propeller' ,Name ='c130',
     planeinfo,!
   ;
     write('enter wing postion'),
     read(Wing),
     (  Wing == 'low' , Name = 'b747',
        planeinfo,!
      ;
        write('enter the bulges type '),
        read(Bulges),
        (  Bulges == 'upperwing' , Name = 'c141', write(Eng),write(Wing),
           planeinfo,!
         ;
           write('enter wing shape '),
           read(Shape),
           write('enter tail '),
           read(Tail),
           planeinfo,
           write("Plane Is Not Found , Please Retry"),
           repeat
        )
     )
  ).

Upvotes: 2

Related Questions