prolog

User input in prolog


I want to write a program that sets cold to true if the user enters winter and sets warm to true if the user enters summer. This is what I have so far:

start :- write('What season is it?: '), read(X), season(X).  
cold :- season(winter).  
warm :- season(summer).

However when I query start and enter winter for the season I get an error that season/1 is undefined. To fix this I tried changing my code to the following:

start :- season(X).  
season(X) :- write('What season is it?: '), read(X).  
cold :- season(winter).  
warm :- season(summer).  

Now when I query start it asks for the season as expected and I entered winter. I queried cold expecting a return of true since I figured season(winter) would be true, but instead I was again prompted to answer "what season is it?". How can I make this simple program work?


Solution

  • Because "cold/0" and "warm/0" take no arguments, it is impossible to change the result at runtime without altering their definition at runtime. The simplest way to do this is just to add or remove the facts "cold." and "warm." depending on user input, using assert/1 and retractall/1.

    start :- write('What season is it?: '), read(X), season(X).
    season(summer) :- retractall(cold), assert(warm).
    season(winter) :- retractall(warm), assert(cold).